【问题标题】:Eloquent push() and save() difference雄辩的 push() 和 save() 的区别
【发布时间】:2013-06-06 19:19:46
【问题描述】:

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

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

保存模型和关系

$user->push();

See link here

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

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    这就是幕后的魔力......

    /**
     * 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() 它将更新该模型及其所有关系 就这样……

    $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();
    

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

    $user->push();
    

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

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

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

    【讨论】:

    • 感谢您的回答...我只有一个问题...关于这一行:$user->state->address = "123 test address"; //This line is a pre-defined relationship 你这是什么意思?这和你在 eloquent like ->hasOne() 中定义的关系一样吗?
    • 是的,这正是我的意思:) hasOne() 类扩展了 Relations 类......这些是 eloquent 在执行 push() 功能时所看到的关系......在上面代码的行中看到......foreach ($this->relations as $models)
    • 谢谢凯尔...我刚刚注意到,如果相关模型在数据库中没有条目,它不会 push()。
    • ->state / ->state->address 分配没有意义。您的示例显示 $user 上的 ->state 是字符串,而不是关系。
    【解决方案2】:

    假设你这样做了:

    $user = User::find(1);
    
    $user->phone = '555-0101';
    $user->address->zip_code = '99950';
    

    您刚刚对两个不同的表进行了更改,要保存它们,您必须:

    $user->save();
    $user->address->save();
    

    或

    $user->push();
    

    【讨论】:

    • @Antonio 如果使用 push() 插入新的关系记录而不是编辑当前记录会怎样?可能吗 ?提前致谢。
    • 如果我实例化 $user = new User() 和 $address = new Address(),并将 $address 分配给 $user->address 会怎样。 push() 会同时保存吗?
    • 看来,push() 不适用于新记录。看到这个问题:github.com/laravel/framework/issues/4641
    【解决方案3】:

    push() 只能用于更新现有模型实例及其关系,而不是创建新模型实例。简单地说: push() 更新而不是插入。

    【讨论】:

    • 这不是真的。
    猜你喜欢
    • 2015-10-01
    • 2017-11-24
    • 2016-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多