首页 > 解决方案 > 如何为其他用户创建模型

问题描述

我一直在做一个项目,我最近开始关注其他用户的用户并看到我正在使用的内容(prisma、graphql 和 nexus)所以今天我创建了一个如下模型,它看起来像这样

model Following {
id       Int    @id @default(autoincrement())
followId Int
User     User?  @relation(fields: [userId], references: [id])
userId   Int?
}

我认为这会起作用,但我意识到它只会将我作为用户返回,而不是我关注的用户,所以我的问题是如何解决这个问题,我会创建另一个模型还是只是在当前模型上重新调整一些东西

标签: typescriptgraphqlnexusprisma

解决方案


如果我没记错的话,对于每个用户,您需要以下内容:

  1. 能够添加/删除User A关注者User B
  2. 查找User关注某个用户的记录。
  3. 查找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的这个概念指南中了解更多关于自我关系的信息。


推荐阅读