【问题标题】:TypeORM - Retrieve data through relation query in resolverTypeORM - 通过解析器中的关系查询检索数据
【发布时间】:2019-09-11 09:54:22
【问题描述】:

所以我试图从 Apollo 解析器中的连接关系中检索元素。

我有一个用户表,一个通知表。还有一个名为:

notification_recipients_user 由两个实体上的多对多关系定义,但托管在 Notification 上:

//entity/Notification.ts
  @ManyToMany(type => User, recipient => recipient.notifications)
  @JoinTable()
  recipients: User[];

我可以通过这种突变毫无问题地创建关系:

    addNotificationForUser: async (_, { id, data }) => {
      const user = await User.findOne({ id });
      if (user) {
        const notification = await Notification.create({
          template: data,
          recipients: [user]
        }).save()
        return notification;
      } else {
        throw new Error("User does not exists!");
      }
    }

但是,我完全没有成功检索特定用户的数据。

    allNotificationsOfUser: (_, { user }, ___) => {
      return Notification.find({
        where: { userId: user },
        relations: ['recipients'],
      })

find 方法是TypeORM 原生方法之一。

但是我一定做错了什么,因为它的反应好像没有任何过滤器一样。

【问题讨论】:

  • 您刚刚插入了多个通知吗?不确定您的问题是否在阅读部分。创建部分将实例化一个新对象(不是从数据库中的旧值中获取),因此您很有可能每次都插入一个新项目,从而在数据库中获得多个。使用原始的 select SQL 查询来检查。
  • @zenbeni 回答 :)

标签: graphql apollo typeorm


【解决方案1】:

好的,最好的方法是使用实​​体之间的关系。

所以要获得通知,您将通过 User.notifications 进行

allUnseenNotificationsOfUser: async (_, { userId }, __) => {
  const user = await User.findOne({
    relations: ["notifications"],
    where: { id: userId }
  });
  if (user) {
    const notifications = user.notifications.filter(notification => !notification.seen)
    return notifications;
  }
  return null;
}

对于遇到此问题的任何人的记录,您可以对结果使用过滤器来执行解析器之类的查询。

const notifications = user.notifications.filter(notification => !notification.seen)

感觉很棘手,但效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2019-09-12
    • 2017-11-18
    • 2023-03-04
    • 2019-03-25
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多