如何将 sql 转换为 Laravel 中的 QueryBuilder
how to convert the sql to QueryBuilder in Laravel
$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 到 select
我无法按照以下方式进行:
$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`)
您应该将 select 列包含在您的 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中禁用only_full_group_by选项。php:
'connections' => [
...
'mysql' => [
...
'strict' => false,
...
],
]
除非您有特殊条件,否则请按您select
的列进行查询分组
$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 到 select
我无法按照以下方式进行:
$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`)
您应该将 select 列包含在您的 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中禁用only_full_group_by选项。php:
'connections' => [ ...
'mysql' => [
...
'strict' => false,
...
],
]
除非您有特殊条件,否则请按您select
的列进行查询分组