You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma数组包含任意元素查询逻辑错误致唯一约束异常排查

Prisma数组唯一约束下的查询与创建冲突

我在Prisma模型中定义了用于存储手机号列表的属性:

phones String[] @unique

当调用API传入包含一个或多个手机号的模型数据时,我希望查询出任意手机号与给定手机号匹配的现有记录,于是编写了以下逻辑代码,但该逻辑存在错误——有时创建记录时会触发唯一约束错误(说明该手机号对应的记录已存在,本应调用更新方法)。

查询与判断逻辑

const body = await request.json();
const records = await prisma.person.findMany({
  where: {
    phones: {
      hasSome: body.phones,
    },
  },
});

if (records.length > 0) {
  const updated = await UpdatePerson(records[0], body); 
  return NextResponse.json(false, {
    status: 200,
  });
} else {
  const created = await CreatePerson(body); 
  return NextResponse.json(false, {
    status: 200,
  });
}

以下是配套的创建、更新方法,以及数组合并辅助方法(作为Prisma新手,欢迎任何建议):

创建方法

async function CreatePerson(data: Person) {
  try {
    const result = await prisma.person.create({
      data,
    });
    return result;
  } catch (error) { 
    throw new Error("创建用户失败");
  }
}

更新方法

async function UpdatePerson(
  existing: Person,
  data: Person,
) {
  try {
    const updatedPerson = await prisma.person.update({
      where: {
        id: existing.id,
      },
      data: {
        ....
        phones: addMissingItems(existing.phones, data.phones),
        email: existing.email ? existing.email : data.email ? data.email : null,

数组合并辅助方法

export function addMissingItems(
  firstArray: string[],
  secondArray: string[],
): string[] {
  // 创建第二个数组的副本,避免修改原数组
  const resultArray = secondArray.slice();

  // 遍历第一个数组的元素
  for (const item of firstArray) {
    // 检查元素是否不在结果数组中
    if (!resultArray.includes(item)) {
      // 将元素添加到结果数组
      resultArray.push(item);
    }
  }

  return resultArray;
}

内容的提问来源于stack exchange,提问作者Nico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:43:34