繁体   English   中英

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

[英]Will Model::updateOrCreate() update a soft-deleted model if the criteria matches?

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

// 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
);

Joe Original现在Joe Updated吗?

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

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

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

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

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

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

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

RoleUser::onlyTrashed()->updateOrCreate(
            [
                'role_id' => $roleId,
                'user_id' => $user->id
            ],
            [
                'deleted_at' =>  NULL,
                'updated_at' => new \DateTime()
            ])->restore();

像这样你创建一个新的或更新一个被软删除的现有的,并将 softDelete 重置为 NULL

我通过@马修- dierckxwith Laravel 5.3和MySQL测试的解决方案,如果该模型更新没有变化(即你正在努力更新与相同的旧值) updateOrCreate方法返回null和restore()给出了一个Illegal offset type in isset or empty

我通过添加withTrashed使其工作,以便在尝试更新或创建时包含软删除的项目。 确保deleted_at位于模型的可填充数组中。

$model = UserRole::withTrashed()->updateOrCreate([
            'creator_id' => $creator->id,
            'user_id' => $user->id,
            'role_id' => $role->id,
        ],[
            'deleted_at' => NULL
        ])->fresh();

试试这个逻辑。。

foreach ($harga as $key => $value) {
    $flight = salesprice::updateOrCreate(
        ['customerID' => $value['customerID'],'productID' => $value['productID'], 'productCode' => $value['productCode']],
        ['price' => $value['price']]
        );
}

它对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM