简体   繁体   中英

Querying for unique composite fields with Prisma

I have an account field in my Postgres DB that has both a username, and an organization that it belongs too. These fields together have to be unique, meaning multiple users can have the same username, but multiple users in the same organization can not have the same username.

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)
);

When using Prisma in NodeJs to query the account by username+organization_id to get the exact user I use this query:

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

However, the query is failing with the messages:

Argument where of type accountWhereUniqueInput needs exactly one argument, but you provided username and organization_id. Please choose one. Available args:

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

Unknown arg 'username' in where.username for type accountWhereUniqueInput. Did you mean 'user_id'? Available args:

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

I figured out the answer shortly after posting. You need to determine the compound key that was created for the fields, and query that composite field directly by passing in the two fields as an object as the value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM