使用 Prisma 查询唯一的复合字段

Das*_*sto 1 postgresql node.js prisma

我的 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)
);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

type accountWhereUniqueInput {
  user_id?: Int
  customer_id?: String
  organization_id?: Int
  account_username_organization_id_key?: Account_username_organization_id_keyCompoundUniqueInput
}
Run Code Online (Sandbox Code Playgroud)

类型 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
}
Run Code Online (Sandbox Code Playgroud)

Das*_*sto 5

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

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