简体   繁体   中英

Laravel: Editing one-to-many relationship fields

I have a table structure similar to this:

id   name   superpower
 1     A      speed
 2     A      stamina
 3     B      speed
 4     C      power
 5     B      power
 6     D      sarcasm

Name has a one-to-many relationship to Superpower. To edit these fields, the front-end form returns an array of superpowers for the name. Ie, the 'edit A' form could return ['speed','power'] (removing stamina and adding power).

An easy way to do this with pure PHP is to remove all superpowers of the name and add the new ones. What is the best way to do this in Laravel?

So you have a User model (for auth), a Kid model for the details of the kids, and then Superpower model for the details of the superpowers.

You have two options that I see. Option one requires a bigger structural change, but easier controller logic while the other is heavier in the controller.

1 -

Create a many-to-many relationship with the kids and superpowers. This may not fit your use case if the users can add new superpowers that are viewable to all other users. This would involve a pivot table that would store each connection between a kid and a superpower.

When returning an array of superpowers to link to a kid (let's say a checkbox list is being submitted in a form), you can use the relationships' sync method:

$kid->superpowers->sync($superpowers);

2 -

If you want to keep your relationships basically how they are, I recommend at least changing the table structure you proposed in your question so that the name field is kid_id . This would be more standard so that a kid would have a hasMany relationship to superpowers and a superpower would have a belongsTo with a kid.

Then you could call:

foreach ($request->superpowers as $superpower) {
    $superpowers[] = ['superpower' => $superpower];
}

$kid->superpowers->delete();
$kid->superpowers->createMany($superpowers);

A noticable downside to this approach is that the data is being removed first in order to sync. The resulting created_at timestamps would then be incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM