Eloquent push()和save()的区别

Mel*_*vin 49 laravel eloquent laravel-4

我已经阅读了关于雄辩的laravel 4文档,并且对push()部分非常感兴趣.它说,

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

拯救模型和关系

$user->push();

请看这里的链接

对不起,但是我在save()和push()之间的区别有点模糊.我希望有人可以为我清除这一个.谢谢.

Kyl*_*lie 88

继承人幕后的魔力......

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

它只是显示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
Run Code Online (Sandbox Code Playgroud)

如果你在这里......

$user->save();
Run Code Online (Sandbox Code Playgroud)

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

$user->push();
Run Code Online (Sandbox Code Playgroud)

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

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

希望这会清除事情....


Ant*_*iro 32

假设你这样做了:

$user = User::find(1);

$user->phone = '555-0101';
$user->address->zip_code = '99950';
Run Code Online (Sandbox Code Playgroud)

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

$user->save();
$user->address->save();
Run Code Online (Sandbox Code Playgroud)

要么

$user->push();
Run Code Online (Sandbox Code Playgroud)