1055在ManyToMany关系laravel 5.3中,SELECT列表的表达式#3不在GROUP BY子句错误中

A.B*_*per 2 php mysql laravel laravel-5.3

我有这样的Post模型:

class Post extends Model
{
        protected $primaryKey = 'post_id';
        public function tags ()
        {
            return $this->belongsToMany('App\Tag');
        }

}
Run Code Online (Sandbox Code Playgroud)

Tag模型:

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;
        }
}
Run Code Online (Sandbox Code Playgroud)

(pt_id列是post_tag数据透视表中的主键字段).

如您所见,和Models 之间存在ManyToMany关系.PostTag

对于特定岗位数相关的标记,我添加tagsCount()getTagsCountAttribute()方法Tag模型.

现在假设我想获得标签特定帖子的计数如下:

$post = Post::find($post_id)->get();
return $post->tagsCount
Run Code Online (Sandbox Code Playgroud)

它在laravel 5.2(和旧版本)中对我有用,但在升级到laravel 5.3后,显示以下错误:

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`)
Run Code Online (Sandbox Code Playgroud)

什么是问题,我该如何解决?

Rya*_*yan 8

这与mysql 5.7有关

长话短说,一个解决方案是尝试config/database.php从true变为false:

'mysql' => [
    'strict' => false, //behave like 5.6
    //'strict' => true //behave like 5.7
], 
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此处:https: //stackoverflow.com/a/39251942/2238694