2016-08-29 74 views
2

我有一個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數據透視表中的主鍵字段)。

如您所見,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`) 

什麼是問題,我該如何解決這個問題?

回答

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']); 
     } 
7

這是到mysql 5.7

長話短說相關的,一個解決方案是試圖從真正改變config/database.php爲false:

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

欲瞭解更多信息,請看這裏: https://stackoverflow.com/a/39251942/2238694

+0

我使用相同的MySQL版本爲laravel 5.2和5.3.but但這個問題只發生在5.3。 –

+0

這解決了我的問題。謝謝。 – rotaercz