【问题标题】:Querying for unique composite fields with Prisma使用 Prisma 查询唯一的复合字段
【发布时间】:2020-12-15 10:12:11
【问题描述】:

我的 Postgres 数据库中有一个帐户字段,该字段既有用户名,也有它所属的组织。这些字段一起必须是唯一的,这意味着多个用户可以拥有相同的用户名,但同一组织中的多个用户不能拥有相同的用户名。

create table account (
    user_id serial primary key,
    username varchar not null,
    password varchar not null,
    is_admin bool not null default false,
    organization_id int not null references organization(organization_id) on delete cascade,
    unique (username, organization_id)
);

在 NodeJs 中使用 Prisma 通过 username+organization_id 查询帐户以获取确切用户时,我使用此查询:

export async function getAccountByUsernameAndOrganization(username, organization_id) {
  return runQuery(
    prisma.account.findOne({
      where: {
        username,
        organization_id,
      },
    }),
  );

但是,查询失败并显示消息:

accountWhereUniqueInput 类型的参数需要恰好一个 参数,但您提供了用户名和组织 ID。请选择 一。可用参数:

type accountWhereUniqueInput {
  user_id?: Int
  customer_id?: String
  organization_id?: Int
  account_username_organization_id_key?: Account_username_organization_id_keyCompoundUniqueInput
}

未知参数 类型 accountWhereUniqueInput 的 where.username 中的“用户名”。你是否 意思是'user_id'?可用参数:

type accountWhereUniqueInput {
  user_id?: Int
  customer_id?: String
  organization_id?: Int
  account_username_organization_id_key?: Account_username_organization_id_keyCompoundUniqueInput
}

【问题讨论】:

    标签: node.js postgresql prisma


    【解决方案1】:

    我在发布后不久就找到了答案。您需要确定为字段创建的复合键,并通过将两个字段作为对象作为值传入来直接查询该复合字段。

    export async function getAccountByUsernameAndOrganization(username, organization_id) {
      return runQuery(
        prisma.account.findOne({
          where: {
            account_username_organization_id_key: { username, organization_id },
          },
        }),
      );
    }
    

    【讨论】:

    • 您是如何找到“account_username_organization_id_key”的?
    • Nvm,返回的错误告诉了可用的密钥
    猜你喜欢
    • 2021-07-17
    • 2014-09-15
    • 2016-03-29
    • 2013-01-06
    • 2021-08-05
    • 2022-09-27
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多