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

Prisma1 schema设计与数据迁移:插入location ID数组到service表报错

问题根因

你需要关联的是已经存在的Location记录,而非创建Service时同步新建Location,LocationCreateManyInput/LocationCreateInput都是用于新建Location的输入类型,和你传已有ID的场景完全不匹配,所以会报类型错误。

解决步骤

1. 修正Schema关系定义

首先要给关联字段加@relation指令,明确多对多关联关系(一个Location可以被多个Service禁用),部署后Prisma才会生成对应关联操作的输入类型:

type Location {
  id: ID! @id
  name: String!
  image: String!
  currency : String!
  lpf: Float!  
  email: String!
}

type Service {
  id: ID! @id
  name: String!
  lastSlot: String
  # 新增关系指令,指定关联名
  disableLocations: [Location!] @relation(name: "ServiceDisabledLocations")
  startPrice: Json
  hasNote: Int! @default(value: 1)
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}

2. 调整Mutation写法

关联已有记录需要用connect操作符,不能直接把ID数组赋值给disableLocations字段:

mutation createService($name: String!, $lastSlot: String!, $disableLocations: [LocationWhereUniqueInput!]!) {
  createService(
    data: {
      name: $name,
      lastSlot: $lastSlot,
      disableLocations : {
        # 用connect关联已有Location
        connect: $disableLocations
      }
    }
  ){
    name,
    lastSlot,
    disableLocations { 
      id
    }
  }
}

3. 前端参数适配

把你传的字符串ID数组,转换成Prisma要求的唯一匹配格式:

axios({
    url: HOST_GRAPHQL,
    method: 'post',
    data: {
        query: `/* 上面写好的mutation */`,
        variables: {
            name: ele.name,
            lastSlot: ele.lastSlot,
            // 把字符串ID转成{id: xxx}的格式
            disableLocations: ele.disableLocations.map(id => ({id}))
        }
    }
}).then((result) => {
    console.log(result, "result-----");
});
扩展说明

如果后续需要修改Service的禁用Location列表,可以用set操作直接覆盖整个关联数组,或者用disconnect操作取消指定Location的关联,不需要修改原始Location数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:36:03