首页 > 解决方案 > Laravel updateOrCreate 与 where 子句

问题描述

如何使用 where 子句实现updateOrCreate函数。

例如。仅当某些列包含特定值时,我才想更新字段,否则不更新。是否可以使用updateOrCreate功能?

标签: laraveleloquent

解决方案


updateOrCreate是 where 子句的更新:

$user = User::updateOrCreate(
    [
        'id'    => $userId,
        'type'  => $userType,
    ], 
    [
        'name'  => $userName,
        'email' => $userEmail,
    ]
);

此查询将使用 and 更新用户,$userName如果$userEmail用户存在匹配$userIdand $userType。如果没有找到匹配的用户,则使用、$userId和来创建一个新用户。$userType$userName$userEmail

因此,第一个数组是更新时必须匹配的“where-clause”,第二个数组是如果找到匹配项则应更新的值,如果没有匹配项,则在创建新用户时使用两个数组的合并成立。

在此处查看文档


推荐阅读