Laravel:Eloquent 如何一次性更新模型和相关模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17950118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:33:53  来源:igfitidea点击:

Laravel: Eloquent how to update a model and related models in one go

laravellaravel-4eloquent

提问by MvdP

Does anyone know if it is possitble to do the folowing:

有谁知道是否可以执行以下操作:

Let's say we have a model called User and a model calledd BestFriend. The relation between the User and the best friend is 1:1.

假设我们有一个名为 User 的模型和一个名为 BestFriend 的模型。用户和最好的朋友之间的关系是 1:1。

I would like for these cases be able to do something like this, change my city and the city of my friend at the same time.

我希望这些案例能够做这样的事情,同时改变我的城市和我朋友的城市。

$me = User::find(1);

$me->update(array(
'city' => 'amsterdam',
'bestfriend.city' => 'amsterdam'
));

So basically I would like to know if Eloquent is smart enough to understand the relationship based on the array key 'bestfriend.city'.

所以基本上我想知道 Eloquent 是否足够聪明来理解基于数组键“bestfriend.city”的关系。

Thanks in advance for any help!

在此先感谢您的帮助!

Update:

更新:

Found the solution on the Laravel forums but im posting it here as well if someone else is looking for the same thing :)

在 Laravel 论坛上找到了解决方案,但如果其他人正在寻找同样的东西,我也会在这里发布它:)

In the model you add

在您添加的模型中

// In your model...
public function setBestFriendArrayAttribute($values)
{
    $this->bestfriend->update($values);
}

And then you can call it like this

然后你可以这样称呼它

$me->update(array(
    'city' => 'amsterdam',
    'BestFriendArray' => array(
        'city' => 'amsterdam'
    )
));

Works like a charm!

奇迹般有效!

回答by dakine

You don't need to set it on your model. You can do it on your controller like this.

你不需要在你的模型上设置它。您可以像这样在控制器上执行此操作。

$me = User::find(1)->bestFriend()->update(array(
'city' => 'amsterdam',
'bestfriend.city' => 'amsterdam'
));

I just modified your update a little bit.

我只是稍微修改了您的更新。

回答by user1669496

Eloquent is pretty smart, but I don't believe it can do that. You would have to update User and BestFriend independently. But once you've done that, Eloquent does have methods for attaching the two.

Eloquent 非常聪明,但我不相信它可以做到这一点。您必须独立更新 User 和 BestFriend。但是一旦你这样做了,Eloquent 确实有将两者联系起来的方法。

$me = User::find(1);
$bff= BestFriend::find(1);

$me->city = 'amsterdam'; 
$bff->city = 'amsterdam';

$me->bestfriend()->associate($bff);

This is of course assuming your User model has a function that looks like...

这当然是假设你的 User 模型有一个看起来像......

public function bestfriend()
{
    return $this->hasOne('BestFriend');
}