how to create relatedWords relation for each words using drizzle. | DRIZZLE | SQL |

Hi folks,

I'm building an online Turkish dictionary using t3 stack with drizzle. I want every word can have related words so that I can show them in related words section when a word searched.
What I tried is to create another table called relatedWords that includes an id and relatedWordId in order to create many-to-many relationship between word and relatedWords.
Here's what I tried with drizzle schemas and relations:
//schema.ts
 
export const words = pgTable("words", {
  id: serial("id").primaryKey(),
  name: varchar("name", { length: 255 }).notNull(),
  phonetic: varchar("phonetic", { length: 255 }),
  root: varchar("root", { length: 255 }),
  attributes: varchar("attributes", { length: 255 }),
  audio: varchar("audio", { length: 255 }),
  createdAt: date("createdAt").notNull(),
  updatedAt: date("updatedAt").notNull(),
});

export const wordsRelations = relations(words, ({ many }) => ({
  wordMeanings: many(meanings),
  wordsToRelatedWords: many(wordsToRelatedWords),
}));

export const relatedWords = pgTable("related_words", {
  id: serial("id").primaryKey(),
  relatedWordId: integer("related_word_id")
    .notNull()
    .references(() => words.id),
});

export const relatedWordsRelations = relations(relatedWords, ({ many }) => ({
  wordsToRelatedWords: many(wordsToRelatedWords),
}));
export const wordsToRelatedWords = pgTable(
  "words_to_related_words",
  {
    wordId: integer("word_id")
      .notNull()
      .references(() => words.id),
    relatedWordId: integer("related_word_id")
      .notNull()
      .references(() => relatedWords.id),
  },
  (t) => ({
    pk: primaryKey({ columns: [t.wordId, t.relatedWordId] }),
  })
);

export const wordsToRelatedWordsRelations = relations(
  wordsToRelatedWords,
  ({ one }) => ({
    words: one(words, {
      fields: [wordsToRelatedWords.wordId],
      references: [words.id],
    }),
    relatedWords: one(words, {
      fields: [wordsToRelatedWords.relatedWordId],
      references: [words.id],
    }),
  })
);

Drizzle studio throws this error: Error: There is not enough information to infer relation "__public__.relatedWords.wordsToRelatedWords"

It's been a while since I created SQL relationships last time and I've never done such a relationship like this. Thanks in advance for any help!
Was this page helpful?