如果条件匹配,Model::updateOrCreate() 会更新软删除的模型吗?

rya*_*ter 5 laravel eloquent laravel-5

假设我有一个被软删除的模型并具有以下场景:

// EXISTING soft-deleted Model's properties
$model = [
    'id'         => 50,
    'app_id'     => 132435,
    'name'       => 'Joe Original',
    'deleted_at' => '2015-01-01 00:00:00'
];

// Some new properties
$properties = [
    'app_id'     => 132435,
    'name'       => 'Joe Updated',
];

Model::updateOrCreate(
    ['app_id' => $properties['app_id']],
    $properties
);
Run Code Online (Sandbox Code Playgroud)

Joe Original现在是Joe Updated吗?

或者是否有已删除的记录和新Joe Updated记录?

小智 16

$variable = YourModel::withTrashed()->updateOrCreate(
    ['whereAttributes' => $attributes1, 'anotherWhereAttributes' => $attributes2],
    [
        'createAttributes' => $attributes1,
        'createAttributes' => $attributes2,
        'createAttributes' => $attributes3,
        'deleted_at' => null,
    ]
);
Run Code Online (Sandbox Code Playgroud)

创建一个新的或更新一个被软删除的现有对象并将 softDelete 重置为 NULL

  • 很好的解决方案,只需记住将“deleted_at”添加到模型的可填充属性即可!;) (4认同)

jed*_*ylo 9

updateOrCreate将查找deleted_at等于NULL的模型,因此它不会找到软删除的模型。但是,因为它找不到,所以它会尝试创建一个新的,从而导致重复,这可能不是您所需要的。

顺便说一句,您的代码中有错误。Model::updateOrCreate将数组作为第一个参数。

  • 这里请注意 - 至少在 5.5 中,“Model::withTrashed()->updateOrCreate()”是有效的并且按预期工作,但记录未恢复。我也无法链接“restore()”方法,因此必须检查返回的模型是否为“trashed()”,然后调用“restore()”。 (5认同)

Ale*_*lex 5

Model::withTrashed()->updateOrCreate([
   'foo' => $foo,
   'bar' => $bar
], [
   'baz' => $baz,       
   'deleted_at' => NULL     
]);
Run Code Online (Sandbox Code Playgroud)

按预期工作(Laravel 5.7) - 更新现有记录并“取消删除”它。

  • Model 在 Laravel 5.8 中仍然被删除。可以通过 Model::withTrashed()->updateOrCreate(['foo' => $foo], ['baz' => $baz])->restore()` 来取消删除 (2认同)