我想使用 Laravel 5
Query Builder 在查询中生成 SUM。
return DB::table('table1')->join('table2','table1.id','=','table2.id')
->where('table1.user_id','=',$userId)
->whereMonth('table2.date', '=', $month )
->whereYear('table2.date', '=', $year )->select('table2.*', DB::raw('SUM(table1.count) AS count_single'))->groupby('table2.id')->get();
但我的问题是我有一个前缀表(xc_),并且DB::raw返回错误
"Column not found: 1054 Unknown column 'table1.count' "
这是前缀表的问题,因为如果我输入:
$table_prefix = env('DB_TABLE_PREFIX', 'xc_');
DB::raw('SUM('.$table_prefix.'table1.count) AS count_single')
有效,所以问题出在前缀上,但我不喜欢这种方法,所以: 有没有不用指定前缀表就可以使用DB::Raw的方法?
最佳答案
DB::raw()
is use to create a raw expression, so you have to use full table name.
Laravel 查询生成器有一个内置函数用于获取表前缀 DB::getTablePrefix()
将上面的代码替换成这个就可以了。
return DB::table('table1')
->join('table2', 'table1.id', '=', 'table2.id')
->where('table1.user_id', '=', $userId)
->whereMonth('table2.date', '=', $month)
->whereYear('table2.date', '=', $year)
->select('table2.*', DB::raw('SUM(' . DB::getTablePrefix() . 'table1.count) AS count_single'))
->groupby('table2.id')
->get();
https://stackoverflow.com/questions/39913958/