dongnei3634 2016-10-07 09:30
浏览 1541
已采纳

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

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

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

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?

  • 写回答

1条回答 默认 最新

  • duanluanlang8501 2016-10-07 11:19
    关注

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


    Reference:
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?