【问题标题】:how to convert the sql to QueryBuilder in Laravel如何在 Laravel 中将 sql 转换为查询生成器
【发布时间】:2021-02-23 12:15:40
【问题描述】:
$old_records = DB::connection("mysql_old_s")->table('leads')
        ->select(DB::raw('count(*) as  source_count, source'))
        ->groupBy('source')
        ->get();
dd($old_records); // works right

这个查询工作正常。 我想再添加一列,例如 id 或 created_at 来选择

我不能这样做:

$old_records = DB::connection("mysql_old_s")->table('leads')
        ->select('id',DB::raw('count(*) as source_count, source'))
        ->groupBy('source')
        ->get();
dd($old_records); // it gives an error

它给了我一个错误:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP 
BY clause and contains nonaggregated column 'crmclini_crmv2.leads.id' which is not functionally 
dependent on columns in GROUP BY
clause; this is incompatible with sql_mode=only_full_group_by (SQL: select `id`, count(*) as 
source_count, source , id from `leads` group by `source`)

【问题讨论】:

    标签: laravel eloquent laravel-query-builder laravel-8


    【解决方案1】:

    您应该在 group by 子句中包含您选择的列以按它们分组:

    $old_records = DB::connection("mysql_old_s")->table('leads')
            ->select('id',DB::raw('count(*) as source_count, source'))
            ->groupBy(['id','source'])
            ->get();
    

    第二个选项(女巫我不推荐),你可以在config/database.php中禁用only_full_group_by选项:

    '连接'=> [ ...

    'mysql' => [
    ...
        'strict' => false,
        ...
    
    ],
    ]
    

    除非您有特殊情况,否则按您选择的列进行查询分组

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2021-08-07
      • 2017-06-01
      • 2019-09-08
      • 2017-04-22
      • 2023-01-14
      • 2019-10-14
      • 2015-12-13
      • 2019-06-21
      相关资源
      最近更新 更多