提问者:小点点

用Prisma查询唯一复合字段


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

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类型的参数where只需要一个参数,但您提供了username和organization_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中存在未知参数“username”。您的意思是“user_id”吗?可用参数:

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

共1个答案

匿名用户

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

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