laravel - 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');
}
}
解决方案
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']);
});
}
推荐阅读
- dataframe - dataframe to_datetime not reading dates correctly
- javascript - How to search for a string in array of arrays using javascript function
- javascript - Babel showing unexpected error, couldn't find the solution
- c++ - 如何置换二进制字符串以最小化它们之间的距离?
- php - PHP脚本不从表单发送变量
- unity3d - 在 Unity 中淡入淡出复杂的游戏对象
- angular6 - 在 Provider 中使用 useValue 时无法编译代码
- html - 在浏览器上播放音频
- supervisord - supervisord http://localhost:9001 拒绝连接
- php - 在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #2 包含非聚合列“abid”;