更新Laravel关系数据

4
当我们通过Eloquent关联模型插入或更新数据时,最好使用哪种方法?
例如:
$user->profile->update(['salary' => 5000]);

vs
 
$user->profile()->update(['salary' => 5000]);

我明白了
  1. $user->profile() 将返回关系类,例如 Illuminate/Database/Eloquent/Relations/HasOne
  2. $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()

更新

参考链接(为了自己的理解)

结论

目前,在应用程序中将使用以下代码,两者都将触发事件。

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
}

1
如果您正在使用php8,您可以使用一个空值安全的方法调用$user->profile?->update() - Spirit
1
我觉得这个问题看起来很熟悉... 很高兴我不必再解释一遍 ;) - lagbox
是的,我正在尝试写下每个方法的场景以及优缺点,这样我就可以避免在我的代码中犯这些错误。 - cww
2
不确定问题中是否提到,但其中一种方法将涉及Eloquent事件,而另一种则不会...在调用模型实例上的update时,将触发模型事件,因为save被调用;另一种方法是直接在构建器上进行update调用,因此没有模型事件。 - lagbox
1
谢谢,你的评论正是我正在寻找的答案。 :) - cww
1个回答

0

你可以使用 forceFill() 函数

示例:

$user->bank->forceFill($data)->save();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接