lundi 4 mars 2019

Passing 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:

  • Added ->withPivot('work_order_id') to the Aircraft and Task models in the appropriate belongsToMany relationships
  • Updated my query to read $aircraft->logbook_entries()->sync([1 => ['work_order_id' => $workorder->id], $request['tasks']]);

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]);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire