我有很多關系,試圖更新資料透視表 order_services。
我的控制器中有這個更新功能:
$order->update($data);
$order->services()->detach();
foreach ($request->services as $service) {
$order->services()->attach($service['service'], [
'quantity' => $service['quantity'],
'price' => $service['price'],
'total' => $service['total']
]);
}
刀片頁面:
<div class="flex">
<button class="mx-1 mt-1 btn btn-primary"
type="button" @click="adjustBy(o,-1)">-</button>
<input type="hidden" x-bind:name="`services[${index}][service]`" :value="o.id">
=
<input type="number" min="1" class="input"
{{--name="quantity[]"--}}
x-bind:name="`services[${index}][quantity]`"
:value="o.quantity"/>
<button class="mx-1 mt-1 btn btn-primary" type="button" @click="adjustBy(o, 1)"> </button>
</div>
<div class="mx-1" x-text="o.total"></div>
<input type="hidden" x-bind:name="`services[${index}][price]`" :value="o.total">
<input type="hidden" x-bind:name="`services[${index}][total]`" :value="o.total">
<div>
這段代碼的問題是它洗掉了一個 previos 并僅在我沒有洗掉 previos 值時才附加一個新值。
如何修復代碼以列印舊值(如果沒有洗掉)和新值。
任何人都可以幫忙嗎?
uj5u.com熱心網友回復:
在您的代碼示例中,您首先洗掉所有 OrderService 資料透視記錄。
當嘗試添加(通過附加功能)新的資料透視記錄時,從您的評論中我們可以看到您在附加功能中傳遞了 NULL 值而不是服務 ID。這將失敗,因為它需要通過和 item ID。
如果您的$request資料包含所有應該與您更新的訂單相關的服務,您可以使用sync()來保存您的新資料。這樣你可以:
- 洗掉 中不存在的資料透視記錄
$request, - 保持存在的存在
- 并添加也存在于
$request.
如果不想洗掉 中不存在的資料透視記錄$request,而只想添加新記錄并更新現有記錄,則可以syncWithoutDetaching()改用。
$order->services()->sync([
1 => ['quantity' => 1, 'price' => 3, 'total' => 3],
2 => ['quantity' => 3, 'price' => 4, 'total' => 12]
]);
您可以在實際同步之前準備同步物件
$syncObject = [];
foreach ($request['services'] as $service) {
$syncObject[$service['id']] = [
'quantity' => $service['quantity'],
'price' => $service['price'],
'total' => $service['total']
];
}
進而
$order->services()->sync($syncObject);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322104.html
