雄辩的push()和save()差异 [英] Eloquent push() and save() difference

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

问题描述

我已经阅读了laravel 4关于雄辩的文章,并对push()部分感兴趣。
它说,


有时你不仅可以保存模型,还可以保存所有的关系。为此,您可以使用推送方法:



保存模型和关系



$ user-> push();


看到这里的链接



对不起,我有一点模糊,save()和push()之间的区别, 。
我希望有人能为我清除这一个。谢谢你。

解决方案

pre> / **
*保存模型及其所有关系。
*
* @return bool
* /
public function push()
{
if(!$ this-> save())return假;

//要将所有关系同步到数据库中,我们将简单地通过
//关系,并通过这种推方法保存每个模型,这允许
//我们递归到模型实例的所有这些嵌套关系中。

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

返回true;
}

只是显示push()将更新与模型相关的所有模型有问题,所以如果你改变任何关系,然后调用push()
它会更新该模型,并且所有的关系
像这样...

  $ user = User :: find(32); 
$ user-> name =TestUser;
$ user-> state =Texas;
$ user-> location-> address =123 test address; //这行是一个预定义的关系

如果这里你只是...

  $ user-> save(); 

然后地址不会保存到地址模型....
但是如果你..

  $ user-> push(); 

然后它将保存所有数据,并将地址保存到地址表/模型中,因为您在用户模型中定义了该关系。



Push()还将更新push()的任何用户/模型的所有相关模型的所有updated_at时间戳。 >

希望足够清楚....


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

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:

Saving A Model And Relationships

$user->push();

See link here

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;
}

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

If here you just...

$user->save();

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

$user->push();

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() will also update all the updated_at timestamps of all related models of whatever user/model you push()

Hopefully thats clear enough....

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

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