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:
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型