选择列总和等于Laravel中另一个表上另一列值的所有行

时间:2015-09-13 15:29:33

标签: mysql laravel laravel-5 sum

选择列总和等于Laravel

中另一个表上另一列值的所有行

购买

id | name               | amount
1  | Gamerzone Book     | 40
2  | Recipe Book        | 20
3  | EngineX Book       | 10

付款

id  | purchase_id  | amount  
1     1              25       
2     1              15       
2     2              10   

代码

$query = DB::table('purchases')
        ->select(['purchases.id','purchases.name',
                   DB::raw("IFNULL(sum(payments.amount),0) as total")
            ])
         ->leftJoin('payments','payments.purchase_id','=','purchases.id')
         ->having('amount','=',DB::raw('total'));
         ->groupBy('purchases.id')->get();

当我运行代码时,我收到以下错误 未找到列:1054未知列'金额'在'有条款'

预期结果

id | name               | total
1  | Gamerzone Book       40

我尝试了所有这些,但似乎没有任何工作

$query->where('purchases.amount','=',DB::raw('total'));
$query->having(DB::raw('purchases.amount'),'=',DB::raw('total'));
$query->havingRaw('IFNULL(sum(purchases.amount),0) = purchases.amount');

1 个答案:

答案 0 :(得分:0)

$paymentsQuery = DB::table('payments')->select(DB::raw("IFNULL(sum(payments.amount),0) as total"))->whereRaw('purchases.id = purchase_id')->groupBy('purchase_id');

$purchasesQuery = DB::table('purchases')->select(['id', 'name', 'amount', DB::raw('(' . $paymentsQuery->toSql() . ') as total')])->havingRaw('amount = total')->mergeBindings($paymentsQuery);

$result = $purchasesQuery->get();

$ paymentsQuery将作为子查询工作,以获得每条采购线的总计。

结果我们得到了像:

这样的sql
select `id`, `name`, `amount`, 
(select IFNULL(sum(payments.amount),0) as total from `payments` where purchases.id = purchase_id group by `purchase_id`) as total 
from `purchases` 
having amount = total