消息

Pessimistic Locking in Laravel Eloquent with refreshForUpdate()

发布
Pessimistic Locking in Laravel Eloquent with refreshForUpdate() image

Eloquent has had refresh() for reloading a model from the database, and lockForUpdate() for taking a row lock as part of a query. What it has not had is a way to do both to a model instance. Laravel 13.27 adds refreshForUpdate() , contributed by @史蒂夫鲍曼#61247

它的作用

The method reloads the model by its primary key with FOR UPDATE applied, and updates the instance in place:

民众 功能 refreshForUpdate ()
{
如果 $this -> exists) {
返回 $this ;
}
返回 $this -> refreshUsingQuery
$this -> newQueryWithoutScopes () -> lockForUpdate ()
(英文):
}

refreshUsingQuery() is the same helper behind refresh() . It scopes the query to the model's key, sends it through useWritePdo() so a read replica cannot serve a lock you are about to depend on, calls firstOrFail() , replaces the raw attributes, reloads any relations that were already loaded, and syncs the original attribute state. The only thing refreshForUpdate() adds is the lock.

Before the refreshUsingQuery() method, safely decrementing a product's stock would look like the following:

民众 功能 购买 产品 $产品) : 回复
{
数据库 :: 交易 功能 () 使用 ($product) {
$产品 = 产品 :: 询问 ()
-> lockForUpdate ()
-> 查找或失败 (产品) -> 获取密钥 ());
如果 (产品) -> 库存 === 0 ){
新的 运行时异常 'The product is out of stock.' (英文):
}
$产品 -> 减少 '库存' (英文):
});
// ...
}

Now, you can refresh and lock a model directly using refreshForUpdate() :

民众 功能 购买 产品 $产品) : 回复
{
数据库 :: 交易 功能 () 使用 ($product) {
$产品 -> refreshForUpdate ();
如果 (产品) -> 库存 === 0 ){
新的 运行时异常 'The product is out of stock.' (英文):
}
$产品 -> 减少 '库存' (英文):
});
// ...
}

进一步阅读

保罗·雷德蒙德照片

Laravel News 特约撰稿人。全栈 Web 开发人员兼作家。

Filed in

赞助

laravelcloud logo
Laravel 云

轻松创建和管理服务器,并在几秒钟内部署 Laravel 应用程序。

访问 Laravel Cloud
Compoships: Eloquent Relationships on Multiple Columns image

Compoships: Eloquent Relationships on Multiple Columns

阅读文章
MKSine: A Filament CMS with Plugins, Themes, and Blocks image

MKSine: A Filament CMS with Plugins, Themes, and Blocks

阅读文章
Cancel In-Flight Form Submissions in Inertia.js v3.7 image

Cancel In-Flight Form Submissions in Inertia.js v3.7

阅读文章
Laravel Starter Kits Now Ship with Vite+ image

Laravel Starter Kits Now Ship with Vite+

阅读文章
Mask Query Bindings in Laravel Exception Messages image

Mask Query Bindings in Laravel Exception Messages

阅读文章
whereBinary(): Case-Sensitive MySQL Queries in Laravel image

whereBinary(): Case-Sensitive MySQL Queries in Laravel

阅读文章