Warm tip: This article is reproduced from serverfault.com, please click

Prisma query junction table

发布于 2020-12-09 14:01:44

I have a DB with two tables: races and languages, and a junction table races_languages. The idea being that a race can speak multiple languages, and a language can be spoken by multiple races.

Here's the schema prisma's generated for me:

model Language {
  id              Int            @id @default(autoincrement())
  name            String         @unique
  races_languages RaceLanguage[]

  @@map("languages")
}

model Race {
  id              Int            @id @default(autoincrement())
  name            String         @unique
  races_languages RaceLanguage[] @relation("racesToraces_languages")

  @@map("races")
}

model RaceLanguage {
  race_id     Int
  language_id Int
  languages   Language @relation(fields: [language_id], references: [id])
  races       Race     @relation("racesToraces_languages", fields: [race_id], references: [id])

  @@id([race_id, language_id])
  @@map("races_languages")
}

So far I've managed to allow queries like this to work:

{
  races {
    id
    name
    races_languages {
      languages {
        name
      }
    }
  }
}

I'm wondering if there's a way for me to allow GraphQL queries that look like this from what's above:

{
  races {
    id
    name
    languages {
      name
    }
  }
}

Is there a way to flatten the races_languages part? What if there's another field in races_languages that I want to keep so that it looks like this:

{
  races {
    id
    name
    languages {
      somethingFromRacesLanguages
      name
    }
  }
}

My resolver looks like this:

  Query: {
    races: (root, args, { db }) =>
      db.race.findMany({
        include: {
          races_languages: { include: { languages: true } },
        },
      }),
  },

Questioner
Nicolas SEPTIER
Viewed
0
Ryan 2020-12-09 22:23:30

Unfortunately there's no way to flatten the join/junction table, in your case the RaceLanguage table.

You would need to fetch the data via include as you do above and then flatten it in your application logic itself.

If you do not have extra columns, you can use Implicit many-to-many relationships in which Prisma handles the junction table automatically as described here