我尝试解决标题中的问题。 PlanetScale 尚不支持外键。
这是我当前的架构:
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",
}),
}));
但它说:
错误:没有足够的信息来推断关系“user.followers”
有人可以帮忙吗?
我解决了我的问题,这是代码:
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",
}),
}));