typescript - 如何为其他用户创建模型
问题描述
我一直在做一个项目,我最近开始关注其他用户的用户并看到我正在使用的内容(prisma、graphql 和 nexus)所以今天我创建了一个如下模型,它看起来像这样
model Following {
id Int @id @default(autoincrement())
followId Int
User User? @relation(fields: [userId], references: [id])
userId Int?
}
我认为这会起作用,但我意识到它只会将我作为用户返回,而不是我关注的用户,所以我的问题是如何解决这个问题,我会创建另一个模型还是只是在当前模型上重新调整一些东西
解决方案
如果我没记错的话,对于每个用户,您需要以下内容:
- 能够添加/删除
User A
关注者User B
- 查找
User
关注某个用户的记录。 - 查找
User
某个用户正在关注的记录。
您不一定需要明确定义单独的模型。相反,您可以为此使用many-to-many
自关系。这是您的User
模型在 Prisma Schema 中的样子
model User {
id String @id @default(uuid()) // or whatever your unique id field is.
following User[] @relation("UserFollows", references: [id])
followers User[] @relation("UserFollows", references: [id])
// ...other fields in user table
}
添加/删除某个用户的关注者
如果用户记录已经存在,您可以像这样添加另一个用户作为关注者:
const updatedUser = await prisma.user.update({
where: {
id: followedUserId,
},
data: {
followers: {
connect: { // change to disconect for removing a follower.
id: followerUserId,
},
},
},
});
您还可以通过将呼叫更改为connect
呼叫来从其他用户的关注者中删除用户disconnect
。
查找用户的关注者和关注列表。
您可以这样做以获取user
记录以及他们的关注者和关注列表。
const user = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
followers: true, // list of followers for userId
following: true, // list of users that follow userId
},
});
您可以在 Prisma Docs的这个概念指南中了解更多关于自我关系的信息。
推荐阅读
- python-3.x - 我需要在发票模型中显示合并的日期字段,特别是在发票模型的 date_invoice 字段中
- c++ - 如何在VS项目中静态链接没有dll文件的cpprest?
- java - Python 调用的服务执行程序问题
- css - 根据数据库中的值更改 css
- gremlin - Gremlin.createClient 不是 3.3.4 版本中的函数
- javascript - 从文件上传 html 的 textarea 中删除模糊 | CSS | javascript
- javascript - 如何让机器人找到频道所有者/与作者的 ID 进行比较
- asp.net-core - 当前上下文中不存在 AddAzureAD(与 Azure AD 集成的 Asp.net 核心 Web 应用)
- java - 无法打开java导出的jar文件
- javascript - 将数据传递给另一个组件 OnClick