php 如何在 Laravel 中重新加载关系集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23364276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:40:16  来源:igfitidea点击:

How do I reload a relation collection in laravel?

phpcollectionslaravellaravel-4relationship

提问by Benubird

In laravel, after using attach() or detach() to add or remove something from a relation, the collection has not changed. So if I have a model whose realation contains [1, 2], after this:

在 Laravel 中,在使用 attach() 或 detach() 从关系中添加或删除某些内容后,集合并没有改变。因此,如果我有一个模型,其实现包含[1, 2],在此之后:

$model->relation()->detach(1);
$model->relation()->attach(3);

it will still contain [1, 2]! How do I refresh it?

它仍然会包含[1, 2]!我如何刷新它?

回答by Benubird

You can easily tell laravel to load a relation with a single command:

你可以很容易地告诉 laravel 用一个命令加载一个关系:

$model->load('relation');

Will tell it to refresh the relation collection, and $model->relationwill now show the correct values.

将告诉它刷新关系集合,$model->relation现在将显示正确的值。

Also unloading a relation will be like this:

卸载关系也将是这样的:

$model->unsetRelation('relation')

回答by Sabrina Leggett

If you want to force all your relations to reload on an as-needed basis and you're inside your model, you can use:

如果您想根据需要强制重新加载所有关系并且您在模型中,则可以使用:

$this->relations = [];

回答by James Akwuh

It is possible to use Eloquent query builder:

可以使用 Eloquent 查询构建器:

$freshCollection = $user->roles()->get();

回答by kevinYang

Conclusion: three solutions in here

结论:这里有三个解决方案

$model->load('relation');

unset($model->relation);

$freshCollection = $user->roles()->get();`

回答by Yevgeniy Afanasyev

either just unsetit and let the system reload on demand.

要么只是unset它,让系统按需重新加载。

unset($model->relation)

or

或者

$model->unsetRelation('relation');

And let it be loaded on request.

并根据要求加载。