2016-11-14 30 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添加到分组中。然后查询运行,但返回所有记录和分组不起作用。 –