2016-11-14 56 views
0

我有一個簡單Education模型工作包含以下字段:GROUPBY不正確的口才和查詢設計器laravel

e_id // Primary key 
user_id //foreign key to link to User model 
field 
grade 
university 
country_education 
city_education 
date_of_graduation 

這是我的模型結構:

class Education extends Model 
    { 
     public $primaryKey = 'e_id'; 
     public $timestamps = false; 
     protected $table  = 'educations'; 

     protected $fillable = ['user_id', 'field', 'grade', 'university', 'country_education', 'city_education', 'date_of_graduation']; 

     public function user() 
     { 
      return $this->belongsTo('App\User', 'user_id', 'user_id'); 
     } 

    } 

現在我想根據user_id字段選擇不同的行。到我寫這篇:

$educations = Education::select(['e_id', 'user_id', 'field', 'grade'])->groupBy(['user_id']); 

但低於錯誤發生:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'lms_forms.educations.e_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select `e_id`, `user_id`, `field`, `grade` from `educations` group by `user_id` limit 10 offset 0) 

然後我加入e_id主鍵groupBy(['user_id'])

$educations = Education::select(['e_id', 'user_id', 'field', 'grade'])->groupBy(['user_id','e_id']); 

查詢運行,但返回所有記錄,而不管user_id的區別。

什麼是問題,我該怎麼辦?

+0

MYSQL5.7已經在這方面作出一些改變檢查遷移注HTTPS://dev.mysql。 com/doc/refman/5.7/en/faqs-migration.html您真的應該閱讀MYSQ提供的所有錯誤消息,線索在錯誤消息中 – RiggsFolly

+0

您想要選擇什麼?不同的用戶?我猜用戶可能有多個字段/等級? –

+0

@Olaf Dietsche,每個用戶的地區教育意味着爲每個用戶選擇一種教育。 –

回答

1

你有ONLY_FULL_GROUP_BY模式打開(默認情況下,在MySql 5.7+上設置爲ON)。

這是對最新的mysql版本所做的改進,以避免從查詢結果中刪除行。不要將它與PK分組,而是嘗試將其與其他列分組,以返回正確的結果。

否則,如果你只是想結果

見繼續禁用此模式 - Disable ONLY_FULL_GROUP_BY

+0

當我沒有在groupBy()中包含PK時,顯示該錯誤。因此,我必須將PK添加到分組中。然後查詢運行,但返回所有記錄和分組不起作用。 –