1055在ManyToMany关系laravel 5.3

时间:2016-08-29 08:08:27

标签: php mysql laravel laravel-5.3

我有Post这样的模型:

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

}

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;
        }
}

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

如您所见,PostTag模型之间存在 ManyToMany 关系。

对于特定帖子的计数相关标签,我向tagsCount()模型添加了getTagsCountAttribute()Tag方法。

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

$post = Post::find($post_id)->get();
return $post->tagsCount

它在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`)

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

2 个答案:

答案 0 :(得分:8)

这与mysql 5.7

有关

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

'mysql' => [
    'strict' => false, //behave like 5.6
    //'strict' => true //behave like 5.7
], 

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

答案 1 :(得分:0)

我不尝试@Ryan,但是添加pt_id(post_tag数据透视表中的主键字段),问题解决了:

public function tagsCount ()
        {
            return $this->belongsToMany('App\Post')
                ->selectRaw('count(pt_id) as count')
                ->groupBy(['tag_id', 'pt_id']);
        }