本文介绍了Laravel检查updateOrCreate是否执行了更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中包含以下代码:

I have the following code in my controller:

for($i=0; $i<$number_of_tourists; $i++) {

$tourist = Tourist::updateOrCreate(['doc_number' => $request['doc_number'][$i]],
$tourist_to_update);

}

每次"updateOrCreate"都起作用时,它会执行以下3件事之一:

each time "updateOrCreate" works, it does 1 of 3 things:

1)更新模型即时或

2)创建并保存一个新的OR

2) creates and saves a new one OR

3)使所有内容保持不变(如果已经存在具有此类值的模型).

3) leaves everything unchanged (if model with such values already exists).

我需要检查'updateOrCreate'是否已正确完成1(更新),然后执行一些代码.

I need to check if 'updateOrCreate' has done exactly 1 (updated) and then execute some code.

我该怎么办?

提前谢谢!

推荐答案

您可以这样解决:

$tourist = Tourist::updateOrCreate([...]);

if(!$tourist->wasRecentlyCreated && $tourist->wasChanged()){
    // updateOrCreate performed an update
}

if(!$tourist->wasRecentlyCreated && !$tourist->wasChanged()){
    // updateOrCreate performed nothing, row did not change
}

if($tourist->wasRecentlyCreated){
   // updateOrCreate performed create
}


备注

在Laravel 5.5中,您最终可以检查使用wasChangedisDirty方法是否确实进行了更新.

In Laravel 5.5 you can finally check if updates have actually taken place with the wasChanged and isDirty method.

    如果模型属性已更改但未保存,则
  • isDirty()为true.
  • 如果更改并保存了模型属性,则
  • wasChanged()为true.
  • isDirty() is true if model attribute has been changed and not saved.
  • wasChanged() is true if model attribute has been changed and saved.

还有一个属性(不是方法!)wasRecentlyCreated检查用户是否被创建.

There is also a property (not method!) wasRecentlyCreated to check if user was created or not.

$user = factory(\App\User::class)->create();

$user->wasRecentlyCreated; // true
$user->wasChanged(); // false
$user->isDirty(); // false

$user = \App\User::find($user->id);

$user->wasRecentlyCreated; // false
$user->wasChanged(); // false
$user->isDirty(); // false

$user->vorname = 'Max';

$user->wasChanged(); // false
$user->isDirty(); // true

$user->save();

$user->wasChanged(); // true
$user->isDirty(); // false

//You can also check if a specific attribute was changed:
$user->wasChanged('name');
$user->isDirty('name');

这篇关于Laravel检查updateOrCreate是否执行了更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:57