Farshad
Farshad

Reputation: 2000

how to insert the pivot relationship in laravel

consider i have 2 models that have the pivot relationship many to many between them . now when i want to insert the pivot table how can i achieve it currently i am doing this :

DB::table('model1_model2')
            ->insert([
                'something' => $something,
                'something2' => $something2,
            ]);

and i kinda feel that its not right and i have do save it with some relation ship or sync !! any idea how to do this ? EDIT‌: Added relationship

 public function accommodationRoom()
    {
        return $this->belongsToMany(AccommodationRoom::class)->withPivot('guest_first_name','guest_last_name','guest_cell_phone','guest_nationality_id');
    }

Upvotes: 0

Views: 1023

Answers (1)

Rwd
Rwd

Reputation: 35200

As mentioned in the Inserting & Updating Related Models - Many To Many Relationships documentation:

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

$model1->accommodationRoom()->attach($accommodationRoomId, [
    'something'  => $something,
    'something2' => $something2,
]);

If you're attaching multiple relations then you would would pass a multidimensional array with the keys are the id of the relation and the values are the arrays of additional data:

$model1->accommodationRoom()->attach( [
    1 => ['something'  => $something, 'something2' => $something2,],
    3 => ['something'  => 'something else', 'something2' => $something2,],
]);

The same is true for the sync() method as well.

Upvotes: 2

Related Questions