使用带有 Table 前缀的 DB::raw()

Use DB::raw() with Table prefix

我想用 Laravel 5 查询生成器在查询中求和。

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();

但我的问题是我有一个前缀table (xc_),并且DB::raw return 错误

"Column not found: 1054 Unknown column 'table1.count' "

这是前缀 table 的问题,因为如果我输入:

$table_prefix = env('DB_TABLE_PREFIX', 'xc_');
DB::raw('SUM('.$table_prefix.'table1.count) AS count_single')

有效,所以问题出在前缀上,但我不喜欢这种方法,所以: 有一种使用 DB::Raw 而不指定前缀 table?

的方法

DB::raw() is use to create a raw expression, so you have to use full table name.

Laravel Query Builder 有一个内置函数,用于获取 table 前缀 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();


参考: