M
M
Max2015-08-18 22:43:50
Laravel
Max, 2015-08-18 22:43:50

Saving a many-to-many relationship?

What if there can be several records in the pivot table with the same link IDs, but with a different custom field?
How to save via sync? joxi.ru/GrqenjxUbKZXrz
From the documented example, it is clear that the auxiliary array must be one-dimensional:
$user->roles()->sync([1 => ['expires' => true]]);
And I want to store several values ​​for a product of a specific characteristic, for example, for a specific product and characteristic with id = 1, the size can be either xs or sm:

$product->property()->sync([1 => ['value' => ['xs', 'sm']]]);

As a result, it should turn out like on the screen joxi.ru/GrqenjxUbKZXrz

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D', 2015-08-18
@Denormalization

Through sync, so that they are separate records - no way. You can store in value: separated by commas, in json, in serialized form.

M
Max, 2015-08-19
@kopcapuk

Did it like this:

$list = $this->request->input('propertyList', []);

        $model->property()->detach(array_keys($list));

        foreach ($list as $propertyId => $row) {
            foreach ($row as $key => $value) {
                if (is_array($value)) {
                    foreach ($value as $item) {
                        $model->property()->attach([$propertyId => [$key => $item]]);
                    }
                } else {
                    $model->property()->attach([$propertyId => [$key => $value]]);
                }
            }
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question