postgresql 带有多个多对一关系的drizzle-orm-请在normalizeRelation时指定关系名称

oknwwptz  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(127)

我有两个表和两个关系,我定义如下:

export const games = pgTable('games', {
    id: serial('id').primaryKey(),
    player1Id: integer('player1_id'),
    player1Scores: json('player1_scores'),

    player2Id: integer('player2_id'),
    player2Scores: json('player2_scores'),

    winnerId: integer('winner_id'),
});

export const players = pgTable('players', {
    id: serial('id').primaryKey(),
    email: varchar('email'),
    name: varchar('name', { length: 256 }),
});

export const playersRelations = relations(players, ({ many }) => ({
    games: many(games),
}));

export const gamesRelations = relations(games, ({ one }) => ({
    player1: one(players, { fields: [games.player1Id], references: [players.id] }),
    player2: one(players, { fields: [games.player2Id], references: [players.id] }),
    winner: one(players, { fields: [games.winnerId], references: [players.id] }),
}));

字符串
然而,我得到了gamesRelations的错误消息,即“‘games’和‘players’之间存在多个关系”。如果我从gamesRelation中删除带有'player2'和'赢家'的条目,它就可以工作。但是信息丢失了。
大概错误是相对简单的,但我没有更多的想法,并感谢任何帮助。
错误消息:
“游戏”与“玩家”之间存在多重关系。请在normalizeRelation处指定关系名称

vi4fp9gy

vi4fp9gy1#

这个错误只是告诉你,它发现了许多共享一个引用到玩家的关系,当你查询你的gamesRelations时,它不会知道哪个字段是winnerplayer1player2
您所要做的就是像错误提示的那样,给予player1player2winner关系的名称。
one函数有一个relationName属性,可以通过config传递给。

one(
    your_table, 
    { 
      fields: [...], 
      references: [...], 
      // Optional `relation name` field used for disambiguating relations
      relationName: '...' 
    }
)

字符串
进行以下更改,我认为这将解决您的问题。

export const gamesRelations = relations(games, ({ one }) => ({
  player1: one(players, { fields: [games.player1Id], references: [players.id], relationName: 'game_player1' } ),
  player2: one(players, { fields: [games.player2Id], references: [players.id], relationName: 'game_player2' }),
  winner: one(players, { fields: [games.winnerId], references: [players.id], relationName:  'game_winner' }),
}));


这在文档中没有提到,但你可以在他们的GH repo中找到这方面的代码:
RelationConfig Interface --传递给one的配置类型:https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/relations.ts#L290
createOne函数--上面使用的one函数:https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/relations.ts#L384
createTableRelationsHelpers函数--返回one函数的relations回调函数:https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/relations.ts#L488

相关问题