我有一個Post
模式是這樣的:1055表達SELECT列表中的#3是不是在GROUP BY在多對多關係laravel根據條款5.3
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
數據透視表中的主鍵字段)。
如您所見,Post
和Tag
型號之間存在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`)
什麼是問題,我該如何解決這個問題?
我使用相同的MySQL版本爲laravel 5.2和5.3.but但這個問題只發生在5.3。 –
這解決了我的問題。謝謝。 – rotaercz