我有三个多对多关系的表,Games
,GamesToPlatforms
,Platforms
。如何查询所有Games
,使其具有platforms
键,该键是抛出连接表的与其关联的平台对象数组。
const GamesTable = pgTable(
'games',
{
id: uuid('id').primaryKey().defaultRandom().notNull(),
name: varchar('name', { length: 255 }).notNull(),
backgroundImage: text('background_image').notNull(),
})
const GamesRelations = relations(GamesTable, ({ one, many }) => ({
platforms: many(GamesToPlatformsTable)
})
const GamesToPlatformsTable = pgTable(
'games_to_platforms',
{
gameId: uuid('game_id').notNull(),
platformId: smallint('platform_id').notNull(),
},
(t) => {
return {
uniqueIdx: uniqueIndex(`unique_idx`).on(t.gameId, t.platformId),
}
}
)
const GamesToPlatformsRelations = relations(
GamesToPlatformsTable,
({ one }) => {
return {
platform: one(PlatformsTable, {
fields: [GamesToPlatformsTable.platformId],
references: [PlatformsTable.id],
}),
})
const PlatformsTable = pgTable(
'platforms',
{
id: smallint('id').primaryKey().notNull(),
name: varchar('name', { length: 255 }).notNull(),
imageBackground: text('image_background').notNull(),
},
(platforms) => {
return {
uniqueIdx: uniqueIndex(`unique_idx`).on(platforms.slug),
}
}
)
const PlatformsRelations = relations(PlatformsTable, ({ many }) => {
return {
games: many(GamesToPlatformsTable),
}
})
1条答案
按热度按时间ej83mcc01#
你可以这样做:
你会得到一个这样的数组:
您仍然需要访问连接表,然后访问每个对象中的
platform
属性,因为目前在Drizzle ORM的关系型API API中没有其他方法可以做到这一点。您可以随时将其Map到您需要的任何形状,但我建议您按原样使用它