I have two mysql tables
1. sales (id,buyer_id)
2. sales_items (id,sales_id,item_id,price,quantity)
very simple two tables.
I am having issue while want to update any record,
like when I edit some sales record I can
- add new item
- modify previously added item
- or delete previously added item
Now I want to update sales_items tables also.
What I am doing now is
- first deleting all records of sales in sales_items table
- Add new records
$task = Auth::user()->sales_items()->where(['sales_id'=>1]);
$task->delete();
//$SalesProducts array have all rows
SaleItem::insert($SalesProducts);
code is working but is this correct approach or there is batter way to do that?
I am using Laravel 8 Eloquent and all tables have models
Thanks
My Answer:
> sales()->find($id);
$task->update($request->all());
// Delete all records in sales_items table
SalesItem::where('sales_id', $id)->delete();
// Add new records in sales_items table
foreach($items as $item) {
SalesItem::create([
'sales_id' => $id,
'item_id' => $item['item_id'],
'price' => $item['price'],
'quantity' => $item['quantity']
]);
}
Rate this post
3 of 5 based on 7437 votesComments