TypeORM - 通过解析器中的关系查询检索数据

TypeORM - Retrieve data through relation query in resolver

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

我有一个用户 table,一个通知 table。还有一个名为 table 的关系:

notification_recipients_user 由两个实体上的 ManyToMany 关系定义但托管在 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'],
      })

查找方法是 TypeORM 本机方法之一。

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

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

因此,要获得通知,您需要 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)

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