I have a Post
Model like this:
class Post extends Model
{
protected $primaryKey = 'post_id';
public function tags ()
{
return $this->belongsToMany('App\Tag');
}
}
and a Tag
Model:
class Tag extends Model
{
public function posts ()
{
return $this->belongsToMany('App\Post');
}
public function tagsCount ()
{
return $this->belongsToMany('App\Post')
->selectRaw('count(pt_id) as count')
->groupBy('tag_id');
}
public function getTagsCountAttribute()
{
if ( ! array_key_exists('tagsCount', $this->relations)) $this->load('tagsCount');
$related = $this->getRelation('tagsCount')->first();
return ($related) ? $related->count : 0;
}
}
(pt_id
column is primary key field in post_tag
pivot table).
As you see ,there is a ManyToMany relation between Post
and Tag
Models.
For count related Tags of a specific Post ,I added tagsCount()
and getTagsCountAttribute()
methods to Tag
Model.
Now suppose I want to get tags Count of a specific Post like this :
$post = Post::find($post_id)->get();
return $post->tagsCount
It worked for me in laravel 5.2 (and older versions) but after upgrading to laravel 5.3 , below error is shown:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'aids.post_tag.post_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select count(pt_id) as count, `post_tag`.`tag_id` as `pivot_tag_id`, `post_tag`.`post_id` as `pivot_post_id` from `posts` inner join `post_tag` on `posts`.`post_id` = `post_tag`.`post_id` where `post_tag`.`tag_id` in (145) and `posts`.`deleted_at` is null group by `post_tag`.`tag_id`)
What is Problem and how can I solve that ?