NodeJS Drizzle ORM如何将一个多对多对象的一边作为一个对象数组包含在一个select many中?

sqxo8psd  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(180)

我有三个多对多关系的表,GamesGamesToPlatformsPlatforms。如何查询所有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),
    }
})
ej83mcc0

ej83mcc01#

你可以这样做:

const result: Response = await db.query.GamesTable.findMany({
    with: {
        platforms: {
            columns: {},
            with: {
                platform: true
            }
        }
    }
})

你会得到一个这样的数组:

type Response = {
    id: string;
    name: string;
    backgroundImage: string;
    platforms: {
        platform: {
            id: number;
            name: string;
            imageBackground: string;
        };
    }[];
}[]

您仍然需要访问连接表,然后访问每个对象中的platform属性,因为目前在Drizzle ORM的关系型API API中没有其他方法可以做到这一点。您可以随时将其Map到您需要的任何形状,但我建议您按原样使用它

相关问题