如何在Laravel中将sql转换为QueryBuilder

问题描述

$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`)

解决方法

您应在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选项:

'connections'=> [ ...

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

],]

除非有特殊情况,否则请按选择的列将查询分组

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...