2016-10-07 09:30

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


I would to make a SUM in query with Laravel 5 Query Builder.

return DB::table('table1')->join('table2','','=','')
            ->whereMonth('', '=', $month )
            ->whereYear('', '=', $year )->select('table2.*', DB::raw('SUM(table1.count) AS count_single'))->groupby('')->get();

but my problem is that I have a prefix table (xc_), and DB::raw return error

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

It is a problem with prefix table, because if I put:

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

It work, so the problem is prefix, but I don't like this method, and so: there is a method for use DB::Raw without specifying prefix table?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanluanlang8501 duanluanlang8501 5年前

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

    Laravel Query Builder has an inbuilt function for getting table prefix DB::getTablePrefix()

    Replace the above code with this and it will work.

    return DB::table('table1')
                    ->join('table2', '', '=', '')
                    ->where('table1.user_id', '=', $userId)
                    ->whereMonth('', '=', $month)
                    ->whereYear('', '=', $year)
                    ->select('table2.*', DB::raw('SUM(' . DB::getTablePrefix() . 'table1.count) AS count_single'))

    点赞 评论 复制链接分享