使用 Eloquent 更新现有外键值。

huangapple go评论66阅读模式
英文:

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"
>

huangapple
  • 本文由 发表于 2023年3月4日 01:36:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定