[英]Laravel 5.3 Eloquent updateOrCreate
try {
\DB::beginTransaction();
Model::updateOrCreate( ['id' => $id, 'number' => $number],
['value' => $request->get('value')]
);
\DB::commit();
} catch (\Exception $e) {
\DB::rollBack();
throw new \Exception($e->error());
}
I was working on a task to create a common trait to prevent a record to be updated by multiple users at the same time. 我正在执行一项任务,以创建一个公共特征,以防止多个用户同时更新一条记录。 And, my method was to put hidden input of $data->updated_at in a blade and then to check it when an update request is sent. 而且,我的方法是将$ data-> updated_at的隐藏输入放在刀片中,然后在发送更新请求时检查它。 And there are some cases Laravel's updateOrCreate is used to update or create a new record. 在某些情况下,Laravel的updateOrCreate用于更新或创建新记录。 And, I don't know how to deal with that. 而且,我不知道该如何处理。 Should, I split the methods to create and update or is there any good way to deal with it? 我应该拆分创建和更新方法的方法,还是有什么好的方法可以处理?
You probably want to separate what you are doing. 您可能想分开您在做什么。
I was playing around and came up with this for fun (haven't tested): 我在玩耍,并想出了这个好玩 (未经测试):
Illuminate\Database\Eloquent\Builder::macro('createOrUpdateWhen', function ($attributes = [], $values = [], $when = null) {
$m = $this->firstOrNew($attributes);
if (is_array($when)) {
$when = function ($m) use ($when) {
foreach ($when as $key => $value) {
if ($m->$key != $value) {
return false;
}
}
return true;
}
}
if (! $m->exists || $when($m)) {
$m->fill($values);
}
$m->save();
return $m;
});
$m = M::createOrUpdateWhen($attributes, $values, function ($m) use ($request) {
return $m->updated_at == $request->input('updated_at');
});
$m = M::createOrUpdateWhen(
$attributes, $values, ['updated_at' => $request->input('updated_at')]
);
:-}
$post = Model::where([['id', $id], ['number', $number]])->first();
try {
\DB::beginTransaction();
if (is_null($post)) {
Model::create($input);
} else {
$post->updateWithExclLock($request->get('updated_at'), $input]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.