雄辩的 push() 和 save() 的区别 [英] Eloquent push() and save() difference

查看:21
本文介绍了雄辩的 push() 和 save() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 laravel 4 docs about eloquent 并且对 push() 部分非常感兴趣.它说,

I have read laravel 4 docs about eloquent and was quite intrigued by the push() part. It says,

有时您可能不仅希望保存模型,还希望保存它的所有关系.为此,您可以使用 push 方法:

Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:

保存模型和关系

$user->push();

在此处查看链接

抱歉,我对 save() 和 push() 之间的区别有点模糊.我希望有人可以为我清除这个.谢谢.

Sorry but it's a bit blurry on my part the difference between save() and push(). I am hoping someone can clear this one out for me. Thank you.

推荐答案

这就是幕后的魔力...

Heres the magic behind the scenes...

/**
 * Save the model and all of its relationships.
 *
 * @return bool
 */
public function push()
{
    if ( ! $this->save()) return false;

    // To sync all of the relationships to the database, we will simply spin through
    // the relationships and save each model via this "push" method, which allows
    // us to recurse into all of these nested relations for the model instance.

    foreach ($this->relations as $models)
    {
        foreach (Collection::make($models) as $model)
        {
            if ( ! $model->push()) return false;
        }
    }

    return true;
}

它只是表明 push() 将更新与该模型相关的所有模型,因此如果您更改任何关系,则调用 push()它将更新该模型及其所有关系就这样……

It just shows that push() will update all the models related to the model in question, so if you change any of the relationships, then call push() It will update that model, and all its relations Like so...

$user = User::find(32);
$user->name = "TestUser";
$user->state = "Texas";
$user->location->address = "123 test address"; //This line is a pre-defined relationship

如果你在这里...

$user->save();

那么地址不会被保存到地址模型中......但是如果你..

Then the address wont be saved into the address model.... But if you..

$user->push();

然后它会保存所有的数据,并将地址保存到地址table/model中,因为你在User model中定义了那个关系.

Then it will save all the data, and also save the address into the address table/model, because you defined that relationship in the User model.

push() 还将更新您 push()

希望这能解决问题....

Hopefully that will clear the things....

这篇关于雄辩的 push() 和 save() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆