S
S
semki0962019-05-22 11:48:20
Laravel
semki096, 2019-05-22 11:48:20

How to update records in intermediate table if data has changed?

On the checkout page - I create an order and write the data from the basket into it, write it in a loop

foreach ( $items_cart as $item ) {
    //запись связанных данных в промежуточную таблицу
    $order->product()->attach([ $item['item_id']=>[ 'product_quantity'=>$item['quantity'],'product_color'=>$item['color'] ] ]);
}

But let's say the user decided to return to put something else in the basket, and delete something. So when I return to the checkout page, I need to make changes - delete something that is no longer in the basket and add a new one. And if there are no changes, leave it as is. Can this be done and how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2019-05-22
@semki096

There are 2 ways, simple and dreary.
An easy way is to delete the old data from the trash every time and write new ones.
The tedious way is a combination of array_diff functions to find out which products to add and which to remove

$attached = array_diff($new, $old);
 $deleted = array_diff($old, $new);

S
Sergey Popov, 2019-05-22
@be_a_dancer

laravel has a great sync method. I recommend that you carefully read the documentation before asking such questions.
Search (ctrl + f) for the word sync(

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question