2

我有一个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

对于特定帖子的计数相关标签,我在模型中添加了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`)

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

4

2 回答 2

8

这与mysql 5.7有关

长话短说,一种解决方案是尝试config/database.php从真变为假:

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

有关更多信息,请参见此处: https ://stackoverflow.com/a/39251942/2238694

于 2016-08-31T14:14:39.733 回答
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']);
        }
于 2016-09-06T08:55:31.500 回答