[英]Laravel's updateOrCreate function
I have such table | user_id | code | created_at | updated_at |
我有这样的表
| user_id | code | created_at | updated_at |
| user_id | code | created_at | updated_at |
. 。
I want to create a method, which creates a new one code (if it not exists) for specific user: 我想创建一个方法,该方法为特定用户创建一个新的代码(如果不存在):
public function createCode(Request $request)
{
$request->user()->confirmationCode()->updateOrCreate([
'user_id' => $request->user()->id,
'code' => bin2hex(random_bytes(3)),
]);
}
User
model: User
模型:
public function confirmationCode()
{
return $this->hasOne(ConfirmationCode::class);
}
But createCode()
always creates a new one code for user, even code for that user_id
is already exists. 但是
createCode()
总是为用户创建一个新的代码,即使该user_id
代码已经存在。 What's wrong? 怎么了?
Your syntax for updateOrCreate is incorrect. 您的updateOrCreate语法不正确。 Currently to update it must match both of your inputs.
当前要更新,它必须与您的两个输入都匹配。 You want the following:
您需要以下内容:
public function createCode(Request $request)
{
$request->user()->confirmationCode()->updateOrCreate(
['user_id' => $request->user()->id],
['code' => bin2hex(random_bytes(3))]
);
}
The function matches on the first input array and then if found Updates with the values in the second array. 该函数在第一个输入数组上匹配,然后如果找到,则使用第二个数组中的值更新。 If the matching fails it will create a new record with the values from both arrays.
如果匹配失败,它将使用两个数组中的值创建一个新记录。
https://laravel.com/docs/5.5/eloquent#other-creation-methods https://laravel.com/docs/5.5/eloquent#other-creation-methods
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.