Graphql TypeORM-通过解析器中的关系查询检索数据
所以我试图从Apollo解析器中的连接关系中检索元素 我有一个用户表,一个通知表。以及一个名为: 通知\u收件人\u由两个实体上的多个关系定义但托管在通知上的用户:Graphql TypeORM-通过解析器中的关系查询检索数据,graphql,apollo,typeorm,Graphql,Apollo,Typeorm,所以我试图从Apollo解析器中的连接关系中检索元素 我有一个用户表,一个通知表。以及一个名为: 通知\u收件人\u由两个实体上的多个关系定义但托管在通知上的用户: //entity/Notification.ts @ManyToMany(type => User, recipient => recipient.notifications) @JoinTable() recipients: User[]; 通过这种变异,我可以毫无问题地建立关系: addNoti
//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方法是本机方法之一
然而,我一定是做错了什么,因为它的反应就像没有任何过滤器一样 好的,所以最好的方法是使用实体之间的关系 因此,要获得通知,您将使用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.filternotification=>!通知
这感觉很棘手,但很有魅力。您刚刚插入了多个通知吗?不确定你的问题在阅读部分。“创建”部分将实例化一个新对象,该对象不是从数据库中的旧值中获取的,所以每次插入一个新项时,都有可能在数据库中获得倍数。使用原始的select SQL查询来检查。@zenbeni回答了这个问题: