gpt4 book ai didi

PHP/Laravel : Retrieve new info of Model after save()

转载 作者:行者123 更新时间:2023-12-04 14:14:05 25 4
gpt4 key购买 nike

这是我的问题:我在 sqlserver 数据库中有一个表如下:

Product ( 
id int identity,
reference varchar(12),
name varchar(40)
)

在 laravel 网络应用程序的网页中,我得到了一个表单,名称仅作为字段和提交按钮。
在 DB 端,我创建了一个触发器(而不是插入),它根据生成的 id 更新行的引用。
例子 :
RGX0000123

其中123是生成的ID,RGX是随机生成的。

该流程遵循 Post/Redirect/Get 设计模式。提交后,我想重定向到 URL 中显示引用而不是 ID 的页面。

在 Laravel 的 Controller 中,我使用 Eloquent 保存我的对象并重定向到下一页:
$product->save();
return redirect()->route('next_page', ['reference' => $product->reference]);

我的问题是我可以在保存后获得 id 而不是引用。我不知道 Eloquent 是如何工作的,但是使用 Hibernate(JAVA) 可以通过 session.flush() 解决此类问题,以将对象与数据库中的数据同步。

正在使用快速和肮脏的修复
$product= Product::find($product->id);

有没有更干净的方法来处理这个问题?

最佳答案

尝试刷新对象:

$product->save();
$product->refresh(); // <---

return redirect()->route('next_page', ['reference' => $product->reference]);

documentation :

Refreshing Models

You can refresh models using the fresh and refresh methods. The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:

$flight = App\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 = App\Flight::where('number', 'FR 900')->first();

$flight->number = 'FR 456';

$flight->refresh();

$flight->number; // "FR 900"

关于PHP/Laravel : Retrieve new info of Model after save(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58489339/

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