Convert SQL Query with Subquery to Laravel query

↘锁芯ラ 提交于 2019-12-25 01:44:08

问题


Is it possible to convert my SQL Query to Laravel 4 Query

SQL:

SELECT
  Branch_tbl.ID,
  Branch_tbl.BranchName,
  (
    SELECT
      SUM(Expenses.Expense)
    FROM
      Expenses
    WHERE
     Expenses.BranchID = Branch_tbl.ID 
  ) as 'Total Expenses'
FROM
  Branch_tbl

回答1:


You may try raw expression (maybe it's not to best solution)

DB::table('branch_tbl')
->select(
  'branch_tbl.id',
  'branch_tbl.branchname',
  DB::raw("
  ( select sum(expenses.expense) from expenses where
    expenses.branchid = branch_tbl.id 
  )as 'total expenses'"))->get();

If you have a complex subquery you can separate it:

$subQuery = DB::table('expenses')
        ->select(DB::raw('sum(expenses.expense)'))
        ->whereRaw('expenses.branchid = branch_tbl.id');

DB::table('branch_tbl')
->select('branch_tbl.id','branch_tbl.branchname',
    DB::raw("(" . $subQuery->toSql() . ") as 'total expenses'")
)
->get();

Be careful not to create any SQL injection with raw expression.



来源:https://stackoverflow.com/questions/23826949/convert-sql-query-with-subquery-to-laravel-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!