如何通过where子句实现 updateOrCreate 函数。
例如。我只想在某些列包含特定值的情况下更新字段,否则就不要更新。 可以使用 updateOrCreate 函数吗?
答案 0 :(得分:3)
updateOrCreate主要在更新模型中的一个列值时使用。您不知道该行是否存在的条件。如果该行存在,则仅更新您的列值,否则创建该行。 br />
$update_value = YourModel::updateOrCreate(
['your_checking_column' => 'your_value',],
['your_updated_coumn' => 'your_updated_value']
);
答案 1 :(得分:2)
updateOrCreate 不提供此功能。相反,您可以使用常规的 where 子句,后跟 update 。从您的问题中我看到您根本不需要创建。
Something::where('column', 'value')->first()->update(['otherColumn' => 'some value']);
答案 2 :(得分:0)
updateOrCreate
是带有where子句的更新:
$user = User::updateOrCreate(
[
'id' => $userId,
'type' => $userType,
],
[
'name' => $userName,
'email' => $userEmail,
]
);
如果用户存在匹配的$userName
和$userEmail
,则此查询将使用$userId
和$userType
更新用户。如果找不到匹配的用户,则会使用$userId
,$userType
,$userName
和$userEmail
创建一个新用户。
因此,第一个数组是必须与更新匹配的“ where-clause”,第二个数组是在找到匹配项时应更新的值,并且在创建新用户时使用两个数组的合并找不到匹配项。
答案 3 :(得分:0)
像这样写代码
$update_value = ModelName::updateOrCreate(
['coloumn' => 'your_value',],
['update' => 'update']
);
答案 4 :(得分:0)
如果您尝试基于某些条件设置值,则可以使用三元:
'user_id' => ($request->user_id && is_numeric($request->user_id) ? $request->user_id : \Auth::user()->id)
这等效于说,如果提供了user_id并为数字,则将值设置为$ request-> user_id,否则从经过身份验证的用户那里获取user_id,这是一个更简单的示例:
'user_id' => ($request->user_id ? $request->user_id : null)
如果在请求中提供了user_id,请使用该值,否则将value设置为null。