首页 > 解决方案 > How to update one to many polymorphic relationship?

问题描述

How to update multiple records in One to many polymorphic relationship? I want to update the fields as a group, but how?

Skill Model:

class Skill extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'percentage'];

    /**
     * Get the owning skillable model.
     */
    public function skillable(): MorphTo
    {
        return $this->morphTo();
    }

}

User Model:

class User extends Model
{
    use HasFactory;
 /**
     * Get all of the skill's user.
     * @return MorphMany
     */
    public function skills(): MorphMany
    {
        return $this->morphMany(Skill::class, 'skillable');
    }
}

form fields

标签: laraveleloquentlaravel-8

解决方案


There are a number of ways to do so:

$user->skills->each(function ($skill) {
    $skill->update([...]);
});

$user->skills->each(fn($skill) => $skill->update([...]));

$user->skills->each->update([...]);

$user->skills()->update([...]);

I recommend the first three approaches. Because if there are any model events, those will be fired. Model events won't be fired in the fourth one.

Specifically to your problem, you might want to do something like this in the controller:

public function update()
{

    $skills = collect(request('skill_titles'))
        ->zip(request('skill_percentages'))
        ->map(function ($pair) {
            return [
                'title' => $pair[0],
                'percentage' => $pair[1],
            ]
        });

    $skills->each(function ($skill) use ($user) {
        $user->skills()->where('title', $skill['title'])
            ->update($skill['percentage']);
    });
}

推荐阅读