【问题标题】:How to create model for other User如何为其他用户创建模型
【发布时间】:2021-09-25 17:24:04
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript graphql nexus prisma


    【解决方案1】:

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

    1. 能够添加/删除User AUser B的关注者
    2. 查找关注某个用户的User 记录。
    3. 查找User某个用户正在关注的记录。

    您不一定需要明确定义单独的模型。相反,您可以为此使用many-to-manyself-relation。这是您的 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 的 concept guide 中了解有关自我关系的更多信息。

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2020-03-30
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多