英文:
Update existing foreign key values using eloquent
问题
我正在尝试使用现有的外键值更新多行数据,其中 basket
应该仅链接到外键ID 100
。
示例:
id | title | basket_id (外键链接到另一个表) |
---|---|---|
1 | apple | 100 |
2 | banana | 200 |
2 | kiwi | 300 |
我尝试过的方法:
$fruits = Fruit::whereIn('basket', [200, 300])->get();
foreach ($fruits as $fruit) {
$fruit->update([
"basket_id" => 100
])
}
这个方法可以正常工作,但是当我打印 $fruit
时,在 eloquent 的 relations
属性中仍然会得到旧的 basket_id
。
我是否漏掉了某个步骤?
谢谢。
英文:
I am trying to update multiple rows of data with existing foreign key values where basket
should only link to the foreign ID of 100
.
Example:
id | title | basket_id (foreign key to another table) |
---|---|---|
1 | apple | 100 |
2 | banana | 200 |
2 | kiwi | 300 |
What I have tried:
$fruits = Fruit::whereIn('basket', [200, 300])->get();
foreach ($fruits as $fruit) {
$fruit->update([
"basket_id" => 100
])
}
This works fine, however, when I print $fruit
, I am still getting the old basket_id
in the relations
attribute in eloquent.
Am I missing a step?
Thanks
答案1
得分: 1
为了获取它,您可以在$fruit
对象上使用fresh()
或refresh()
,如下所示:
$fruits = Fruit::whereIn('basket', [200, 300])->get();
foreach ($fruits as $fruit) {
$fruit->update([
"basket_id" => 100
]);
$fruit->refresh(); // 获取更新后的对象
}
https://laravel.com/docs/10.x/eloquent#refreshing-models
fresh
方法将重新从数据库中检索模型。现有模型实例不会受到影响:$flight = Flight::where('number', 'FR 900')->first(); $freshFlight = $flight->fresh();
refresh
方法将使用来自数据库的新数据重新加载现有模型。此外,它的所有加载的关系也将被刷新:$flight = Flight::where('number', 'FR 900')->first(); $flight->number = 'FR 456'; $flight->refresh(); $flight->number; // "FR 900"
英文:
To fetch it, you can use the fresh()
or refresh()
on $fruit
object, like this:
$fruits = Fruit::whereIn('basket', [200, 300])->get();
foreach ($fruits as $fruit) {
$fruit->update([
"basket_id" => 100
]);
$fruit->refresh(); // Fetch updated object
}
https://laravel.com/docs/10.x/eloquent#refreshing-models
> The fresh
method will re-retrieve the model from the database. The existing model instance will not be affected:
>
> $flight = Flight::where('number', 'FR 900')->first();
> $freshFlight = $flight->fresh();
>
>
> The refresh
method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:
>
>
> $flight = Flight::where('number', 'FR 900')->first();
> $flight->number = 'FR 456';
> $flight->refresh();
> $flight->number; // "FR 900"
>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论