如何在laravel重新加载关系集合?

时间:2023-02-03 23:09:54

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]!如何刷新它?

4 个解决方案

#1


48  

You can easily tell laravel to do it with a single command:

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

$model->load('relation');

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

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

#2


3  

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 = [];

#3


3  

It is possible to use Eloquent query builder:

使用有说服力的查询生成器是可能的:

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

#4


0  

conclusion: three solutions in here $model->load('relation'); unset($model->relation); $freshCollection = $user->roles()->get();

结论:这里有三个解$model->load(“关系”);设置($模型- >关系);$ freshCollection = $ user - >角色()- >();

#1


48  

You can easily tell laravel to do it with a single command:

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

$model->load('relation');

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

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

#2


3  

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 = [];

#3


3  

It is possible to use Eloquent query builder:

使用有说服力的查询生成器是可能的:

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

#4


0  

conclusion: three solutions in here $model->load('relation'); unset($model->relation); $freshCollection = $user->roles()->get();

结论:这里有三个解$model->load(“关系”);设置($模型- >关系);$ freshCollection = $ user - >角色()- >();