Andrew Fox
Andrew Fox

Reputation: 890

Passing additional data to the intermediate table using sync() in Laravel 5.1

I've got the following, which works as expected:

$aircraft->logbook_entries()->sync($request['tasks']);

I want to add "work_order_id" to my pivot table, so I've done the following:

This does not add the work_order_id to the pivot table as desired. Instead I get the error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (pams_amo.airframe_logbook_entries, CONSTRAINT airframe_logbook_entries_work_order_id_foreign FOREIGN KEY (work_order_id) REFERENCES work_orders (id)) (SQL: insert into airframe_logbook_entries (aircraft_id, created_at, task_id, updated_at) values (1, 2019-03-04 22:11:48, 12, 2019-03-04 22:11:48))

I followed the Laravel 5.1 Documents: Many To Many Relationships - syncing for convenience that says:

Syncing For Convenience

You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the array will exist in the intermediate table:

$user->roles()->sync([1, 2, 3]);

You may also pass additional intermediate table values with the IDs:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

Upvotes: 1

Views: 1021

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

You misunderstood how the sync method works if you want to pass an additional column. All you have to do is to call the sync method as:

$tasks = array_combine(
    $request['tasks'],
    array_fill(0, count($request['tasks']), ['work_order_id' => $workorder->id])
);

$aircraft->logbook_entries()->sync($tasks);

So, the idea is that if you want to pass an additional parameter to the pivot, the task ID becomes the array key and the additional parameter is sent as the array value

Upvotes: 2

Related Questions