NodeJS 如何使用Drizzle和PlanetScale为同一个表创建多对多关系?

agxfikkp  于 2023-11-17  发布在  Node.js
关注(0)|答案(1)|浏览(136)

我试着解决标题中的问题。PlanetScale还不支持外键。
这是我当前的schema:

export const users = mysqlTable("user", {
  id: varchar("id", { length: 256 }).primaryKey(),
  email: varchar("email", { length: 256 }).unique(),
  username: varchar("username", { length: 256 }).unique(),
  firstName: text("first_name"),
  lastName: text("last_name"),
});

export const usersRelations = relations(users, ({ many }) => ({
  followers: many(following, { relationName: "followers" }),
  following: many(following, { relationName: "following" }),
}));

export const following = mysqlTable("usersFollowing", {
  userId: varchar("user_id", { length: 255 }).primaryKey(),
  followerId: varchar("follower_id", { length: 255 }).notNull(),
});

export const followingRelations = relations(following, ({ one }) => ({
  userId: one(users, {
    fields: [following.userId],
    references: [users.id],
    relationName: "user",
  }),
  followerId: one(users, {
    fields: [following.followerId],
    references: [users.id],
    relationName: "follower",
  }),
}));

字符串
但它说:
错误:没有足够的信息来推断关系“用户.关注者”
有人能帮忙吗?

eufgjt7s

eufgjt7s1#

我解决了我的问题,这是代码:

export const users = mysqlTable("user", {
  id: varchar("id", { length: 256 }).primaryKey(),
  email: varchar("email", { length: 256 }).unique(),
  username: varchar("username", { length: 256 }).unique(),
  firstName: text("first_name"),
  lastName: text("last_name"),
});

export const usersRelations = relations(users, ({ many }) => ({
  followers: many(usersFollowing, { relationName: "followers" }),
  followings: many(usersFollowing, { relationName: "followings" }),
}));

export const usersFollowing = mysqlTable(
  "usersFollowing",
  {
    userId: varchar("user_id", { length: 255 }),
    followingId: varchar("followingId", { length: 255 }).notNull(),
  },
  (table) => ({
    user: index("usersFollowing_user_idx").on(table.userId),
    following: index("usersFollowing_following_idx").on(table.followingId),
  }),
);

export const followingRelations = relations(usersFollowing, ({ one }) => ({
  user: one(users, {
    fields: [usersFollowing.userId],
    references: [users.id],
    relationName: "followers",
  }),
  follower: one(users, {
    fields: [usersFollowing.followingId],
    references: [users.id],
    relationName: "followings",
  }),
}));

字符串

相关问题