John Davidson

php - Laravel Eloquent update related records

0 comments
Message:


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



  1. add new item

  2. modify previously added item

  3. or delete previously added item


Now I want to update sales_items tables also.


What I am doing now is




  1. first deleting all records of sales in sales_items table

  2. 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 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us