gpt4 book ai didi

laravel - Eloquent push()和save()区别

转载 作者:行者123 更新时间:2023-12-03 06:06:48 26 4
gpt4 key购买 nike

我读过关于 eloquent 的 Laravel 4 文档,并且对 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:

Saving A Model And Relationships

$user->push();

See link here

抱歉,我对 save() 和 push() 之间的区别有点模糊。我希望有人能为我解决这个问题。谢谢。

最佳答案

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

/**
* 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();

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

push() 还将更新您 push()

的任何用户/模型的所有相关模型的所有 update_at 时间戳

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

关于laravel - Eloquent push()和save()区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com