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.'
(英文):}$产品
->
减少
(
'库存'
(英文):});
// ...}







