laravel 错误:“方法Illuminate\Database\Eloquent\Collection::update不存在”,如何将多行数据更新到表中?[Eloquent]

yk9xbfzb  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(318)

所以我有这个

$master_item_id = array_map('intval', $request->master_item_id);
        $quantity = array_map('intval', $request->quantity);
        $price = MasterItem::whereIn('id', $master_item_id)->get('price');

        foreach ($master_item_id as $key => $no) {
            $input['price'] = $price[$key]['price'];
            $input['quantity'] = $quantity[$key];
            $subtotal[] = $input['price'] * $input['quantity'];
        }

        $total_price = array_sum($subtotal);

        // Update transaction
        $transaction = Transaction::find($id);
        $transaction->total_price = $total_price;
        $transaction->last_edited_by = Auth::user()->name;
        $transaction->update();

        // Update transaction_item
        foreach ($master_item_id as $key => $no) {
            $transaction = Transaction::find($id);
            $transaction->transaction_item->transaction_id= $transaction->id;
            $transaction->transaction_item->master_item_id = $no;
            $transaction->transaction_item->quantity = $quantity[$key];
            $transaction->transaction_item->price = $price[$key]['price'];
            $transaction->transaction_item->update();
        }

我的模型
x一个一个一个一个x一个一个二个一个x一个一个三个一个
我的表结构

transaction: id(pk), total_price
transaction_item: id(pk), transaction_id(fk), master_item_id(fk), quantity, price
master_item: id(pk), item_name, price

当我尝试更新它弹出错误

Method Illuminate\Database\Eloquent\Collection::update does not exist.

错误突出显示了我的代码中的这一行

$transaction->transaction_item->update();

我如何编辑/更新多行数据?我在模型中的关系是否正确?谢谢!

kxe2p93d

kxe2p93d1#

您正在Eloquent\Collection上调用update()方法,该方法不起作用。您可以尝试以下操作:

// Update transaction_item
foreach ($master_item_id as $key => $no) {
    $transaction = Transaction::find($id);
    $transaction->transaction_item()->update([
        'transaction_id' => $transaction->id,
        'master_item_id' => $no,
        'quantity' => $quantity[$key],
        'price' => $price[$key]['price']
    ]);
}
tgabmvqs

tgabmvqs2#

你需要得到$transaction->transaction_item()而不是$transaction->transaction_item,你变成了Illuminate\Database\Eloquent\Relations\HasMany,然后你可以调用update()方法。

$transaction->transaction_item()->update(['some_field' => 'some_variable']);

相关问题