gpt4 book ai didi

php - groupBy 无法在 laravel 中的 eloquent 和查询构建器中正常工作

转载 作者:行者123 更新时间:2023-11-29 11:10:52 24 4
gpt4 key购买 nike

我有一个简单的Education模型包含以下字段:

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 区别如何。

问题是什么?我能做什么?

最佳答案

试试这个...在文件夹config => database.php中确保mysql strictfalse,像这样

'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],

如果 strict 为 true,则将其设置为 false,然后通过在 cmd 中运行此命令来清除配置现金

php artisan config:clear

关于php - groupBy 无法在 laravel 中的 eloquent 和查询构建器中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com