想象一下,您在某事上有用户和订阅。您需要为用户的订阅进行分页。每个用户都有不同数量的订阅。这是我想到的第一件事:
users = User.where(id:[array]).index_by(&:id) # find users and make an object with id as a key
subs = Subs.where(user_id: [array]).limit(3).offset(1) # find subs for all users what we need
subs.forEach{|s| users[s[:id]].subs << s} # build graphql response
但它不起作用,因为它通常对所有用户进行限制,但我们需要为每个用户。输出应该是这样的:
{
users: [
{
id: 1,
subs: [sub1, sub2] // this user has only two elements and it's like an end of pagination
},
{
id: 2,
subs: [sub3, sub4, sub5] // this user has more items on next page
}
]
}
默认情况下,Graphql 为每个用户进行子查询以使其真实,但它是 n+1。有没有办法让它没有 n+1 并通过 cpu 和内存使用进行优化?