MeeDNite
MeeDNite

Reputation: 159

Laravel Many to Many, attach one model, multiple times

I have a many to many relationship between 2 models: Tours and Locations, and I have some extra pivot-table fields (days and nights of staying in each location).
Everything is set up and working just fine.

Each Tour can have multiple locations, the point is, every tour can have the same location, MULTIPLE times:

----------------------------------------------------
| tour_id | location_id | days | nights | ordering |
----------------------------------------------------  
|    1    |      1      |   4  |    3   |     1    |
----------------------------------------------------  
|    1    |      2      |   5  |    5   |     2    |
----------------------------------------------------  
|    1    |      1      |   2  |    1   |     3    |
----------------------------------------------------  

So we have:

foreach ($locations as $location) {
    $tour->locations()->attach($location->id, [
         'days' => $location->days,
         'nights' => $location->nights,
         'ordering' => $location->ordering
    ]);
}

This will result in adding only 2 rows to pivot table. How can we attach a single Location to a tour, MULTIPLE times?

Regards,

Upvotes: 3

Views: 2035

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

In your loop you are attaching the modal, thus it only adds one relationship. You will have to manually add again, if want an extra relationship.

The loop added all 3 at once. Now you want to add a 4th location ?

$location4 = Location::find(4);

$tour->locations()->attach($location4, [
    'days' => $location4->days,
    'nights' => $location4->nights,
    'ordering' => $location4->ordering
]);

To avoid overriding, use syncWithoutDetaching()

$tour->locations()->syncWithoutDetaching($location4, [
    'days' => $location4->days,
    'nights' => $location4->nights,
    'ordering' => $location4->ordering
]);

Upvotes: 1

Related Questions