Laravel upsert创建重复记录

bis0qfac  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(141)
$responsible_users = collect($request->responsible_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::RESPONSIBLE_ROLE]));
$subordinate_users = collect($request->subordinate_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::DIRECT_SUBORDINATE_ROLE]));

$internal_users = $responsible_users->merge($subordinate_users)->toArray();
OrganizationElementUser::upsert($internal_users, ['user_id', 'organization_element_id', 'type'], ['user_id', 'organization_element_id', 'type']);

为什么我的upsert创建重复记录?
我的user_idorganization_element_idtype字段可以单独重复,但所有3个字段组合在一起会创建唯一记录
例如,我想要的是:

user_id == 1 && organization_element_id == 2 && type == 'test'
//ignore if true otherwise insert
vxf3dgd4

vxf3dgd41#

您可以使用UpdateOrCreate方法。文档在这里。

User::updateOrCreate([
                    'user_id' => $user_id, 
                    'organization_element_id' => 2,
                    'type' => 'test'], //if everything matches with these conditions, the row will get updated, otherwise, it will be inserted. It is like the where clause.
                    ['column_xyz' => $request->new_string],
                );

相关问题