How to add multiple records to a table facilitator in laravel 5.2?

Hello. Use Laravel 5.2 . Faced with the problem of multiple additions to the table facilitator.
There are 3 MySQL tables with the following structure:

objects ( list of objects )
: id

objects_categories ( a list of category objects )
: id

objects_to_categories ( pivot table for above tables )
: object_id, category_id

Page, add objects, you can activate several categories. The object itself needs to get to the table objects and object categories in the table objects_to_categories. I have solve it like this:
- add object
- get the object ID
- get an array of added categories
- add cycle all categories

Not very nice. So. How to solve this problem standard functionality of Laravel 5.2. I would really appreciate your help.
July 9th 19 at 11:22
2 answers
July 9th 19 at 11:24
Solution
July 9th 19 at 11:26
Solution
$object->categories()->attach([1, 2, 3]);
Look, I get the array of categories in this format.
$categories = [
0 => "2"
1 => "4"
2 => "5"
]
---
Record the relationship, as you suggested.
$objectModel->categories()->attach([$categories], ['object_id' => 10]);

Not working.
---
Be written as:
$objectModel->categories()->attach([1, 2, 3], ['object_id' => 10]);

Works fine, adds a few lines
---
Translate to a string $categories
$objectModel->categories()->attach([implode(',', $categories)], ['object_id' => 10]);

Adds only 1 record. I can not understand. - brenden_Johnson commented on July 9th 19 at 11:29
$object->categories()->attach($тут_должен_быть_массив_categories, $pivot_data);
$pivot_data now you do not need.
You need to do so:
$objectModel->categories()->attach($categories); - rahsaan_Be commented on July 9th 19 at 11:32
:
Thank you, In this case, the field object_id, pivot table (objects_to_categories) is NULL
But this option is earned.
$objectModel->categories()->attach($categories ['object_id' => 10]);

In the model Object, the method categories() relationship builds so:
return $this->belongsToMany('App\Models\ObjectCategory', 'objects_to_categories', 'object_id', 'category_id');

As I moved away from the standard? Or all right? - brenden_Johnson commented on July 9th 19 at 11:35
The attitude is correct, but ['object_id' => 10] should the machine be placed.
Do you do that?
$objectModel = Object::create($params);
$objectModel->categories()->attach($categories); - rahsaan_Be commented on July 9th 19 at 11:38
:
Yes, so doing all of that - brenden_Johnson commented on July 9th 19 at 11:41

Find more questions by tags Laravel