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

标签 php mysql laravel

我有一个简单的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/

相关文章:

php - 无法访问现有的 php cookie

mysql - 使用 Mule Studio 读取 CSV

laravel - 如何在路由中使用参数运行 artisan 命令?

php - Laravel 5.2 仅找不到一条特定路线,但它确实存在

php在两个值之间分割数组

javascript - javascript中的php数组连接

php - 如何通过 MYSQL/PHP 将 .sql.gz 文件导入我的数据库? (不是命令行)

mysql - SQL选择2个表

php - 无法将图像上传到laravel中的公共(public)目录

php - 如何从 POST 请求传递数据?