Convert SQL Query with Subquery to Laravel query

2019-08-28 06:39发布

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条回答
叛逆
2楼-- · 2019-08-28 07:09

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.

查看更多
登录 后发表回答