是否可以将我的SQL查询转换为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
答案 0 :(得分:1)
您可以尝试原始表达(也许它不是最佳解决方案)
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();
如果您有一个复杂的子查询,则可以将其分开:
$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();
注意不要使用原始表达式创建任何SQL注入。