mercredi 4 octobre 2017

Create entity and attach on same operation is failing

I have this code:

$entity = new Role();
$data = $request->json()->all();
$entity->fill($data);
foreach ($data['permissions'] as $permission) {
    $entity->perms()->attach($permission['id']);
}
$entity->save();

This is failing with an integrity contraint as it seems that the attach is setting null on the role_id. The role.id is an increments column.

Of course I can move the save before the foreach and save the entity again after that:

$entity = new Role();
$data = $request->json()->all();
$entity->fill($data);
$entity->save();
foreach ($data['permissions'] as $permission) {
    $entity->perms()->attach($permission['id']);
}
$entity->save();

, but that would require to use a transaction.

Is there a more elegant way than saving twice?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire