错误:"Method IlluminateDatabaseEloquentCollection::update does not exist."如何将多行数据更新到表?[雄辩]



这里是

$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();
}

我的模型
// Transaction Model
public function transaction_item()
{
return $this->hasMany(TransactionItem::class, 'transaction_id');
}
public function item()
{
return $this->belongsToMany(MasterItem::class, 'transaction_item', 'transaction_id', 'master_item_id');
}
// TransactionItem Model
public function transaction()
{
return $this->belongsToMany(Transaction::class, 'transaction_id');
}
public function item()
{
return $this->belongsToMany(MasterItem::class, 'master_item_id');
}
// MasterItem Model
public function transaction_item()
{
return $this->hasMany(TransactionItem::class, 'master_item_id');
}

我的表结构

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 IlluminateDatabaseEloquentCollection::update does not exist.

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

$transaction->transaction_item->update();

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

您正在对不工作的EloquentCollection调用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']
]);
}

您需要获得$transaction->transaction_item()而不是$transaction->transaction_item,您成为IlluminateDatabaseEloquentRelationsHasMany,然后您可以调用update()方法。

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

相关内容

  • 没有找到相关文章

最新更新