当我们通过Eloquent关联模型插入或更新数据时,最好使用哪种方法?
例如:
我明白了
有没有任何情况需要使用
或者说,当存在多重嵌套关系时应该使用它吗?
例如:
$user->profile->update(['salary' => 5000]);
vs
$user->profile()->update(['salary' => 5000]);
我明白了
- $user->profile() 将返回关系类,例如 Illuminate/Database/Eloquent/Relations/HasOne
- $user->profile 将返回实际的 UserProfile 模型类
我记得有人推荐使用 $user->profile->update()
而不是 $user->profile()->update()
,但我再也找不到那篇文章或参考链接了
然而,如果 $user->profile
是 null,则可能会导致错误,如:
Call to a member function update() on null
所以,总是使用关系函数更新是否更容易?
$user->profile()->create()
$user->profile()->update()
$user->profile()->save()
$user->profile()->delete()
有没有任何情况需要使用
$user->profile->save()
呢?或者说,当存在多重嵌套关系时应该使用它吗?
$user->profile->bank()->create()
$user->profile()->bank()->create()
更新
参考链接(为了自己的理解)
- https://github.com/laravel/framework/issues/13568
- https://github.com/laravel/framework/issues/2536
- Eloquent attach/detach/sync fires any event?
结论
目前,在应用程序中将使用以下代码,两者都将触发事件。
if ($user->bank === null) {
$user->bank()->save(new UserBankAccount($input)); // trigger created event
// $user->bank()->create($input);// trigger created event
} else {
$user->bank->update($input); // trigger updated event
// $user->bank()->update($input); // will NOT trigger updated event
}
$user->profile?->update()
。 - Spirit;)
- lagboxupdate
时,将触发模型事件,因为save
被调用;另一种方法是直接在构建器上进行update
调用,因此没有模型事件。 - lagbox