Laravel-将RAW查询转换为口才查询(更新查询)

时间:2020-05-27 08:41:17

标签: php mysql laravel laravel-5 eloquent

我有一个名为partner_transaction的表。在此表中,我有4列: id,partner_id,类型,金额

|id|partner_id |type     |amount|
|--|------------|---------|------|
|1 |65          |Credit   |50    |
|2 |65          |Credit   |20    |
|3 |65          |Debit    |30    |
|4 |10          |Credit   |30    |

现在我要在此表上引入一个新的余额列(当前余额),如下所示。

|id|partner_id  |type     |amount|balance|
|--|------------|---------|------|-------|
|1 |65          |Credit   |50    |50     |
|2 |65          |Credit   |20    |70     |
|3 |65          |Debit    |30    |40     |
|4 |10          |Debit    |30    |-30    |

我们要针对特定​​合作伙伴按类型重新调整所有余额列(65)。因此,我们编写了一个原始查询-

update partner_transactions pt
inner join (
select
    id, (select sum(case type when 'Credit' then amount when 'Debit' then -amount end)
    from partner_transactions pt2
    where pt2.partner_id = pt1.partner_id and pt2.id <= pt1.id
    ) balance
    from partner_transactions pt1
    WHERE pt1.partner_id = 65
) ptx
on ptx.id = pt.id AND pt.partner_id = 65
set pt.balance = ptx.balance
WHERE pt.partner_id = 65

我们正在使用Laravel 5.2 。 现在我们要雄辩地转换。所以我们写2函数。

01。用于计算余额-

private function calculateBalanceQuery()
    {
        return DB::table('partner_transactions as pt1')
            ->where('pt1.partner_id', 65)
            ->selectRaw("id, (select sum(case type when 'Credit' then amount when 'Debit' then -amount end)
                from partner_transactions pt2
                where pt2.partner_id = pt1.partner_id and pt2.id <= pt1.id) balance"
            );
    }

02。对于更新partner_transaction_table-

public function updateQuery()
    {
        return PartnerTransaction::join(DB::raw('(' . $this->calculateBalanceQuery()->toSql() . ') ptx'), function ($join) {
                $join->on('ptx.id', '=', 'partner_transactions.id')->on('partner_transactions.partner_id', '=', DB::raw("'65'"));
            })
            ->where('partner_transactions.partner_id', 65)
            ->update(['partner_transactions.balance' => 'ptx.balance']);
    }

但是执行此脚本时,发生了错误。

QueryException in Connection.php line 729:
SQLSTATE[HY093]: Invalid parameter number (SQL: update `partner_transactions` inner join (select id, (select sum(case type when 'Credit' then amount when 'Debit' then -amount end)
from partner_transactions pt2
where pt2.partner_id = pt1.partner_id and pt2.id <= pt1.id) balance from `partner_transactions` as `pt1` where `pt1`.`partner_id` = ptx.balance) ptx on `ptx`.`id` = `partner_transactions`.`id` and `partner_transactions`.`partner_id` = '65' set `partner_transactions`.`balance` = 65 where `partner_transactions`.`partner_id` = ?)

那我们怎么转换呢?

0 个答案:

没有答案