【发布时间】:2021-06-08 11:39:22
【问题描述】:
我正在使用 graphql 和批处理加载器 gem 并遇到这个 N+1 查询:
我有一个属于某个帐户的日历约会,当我们显示约会时间时,我们基于帐户的时区。
def appointment_time
read_attribute(:appointment_time).in_time_zone(self.account.timezone)
end
calendarAppts {
appointmentTime
}
产生 N+1 个查询
POST /graphql
USE eager loading detected
CalendarAppt => [:account]
Add to your query: .includes([:account])
Call stack
/....rb:866:in `appointment_time'
/.../app/controllers/graphql_controller.rb:17:in `execute'
我还有许多其他类似的实例方法创建 N+1 查询的示例,并且不确定解决此问题的最佳方法。
到目前为止,我刚刚看到了直接征服急切加载关联的方法。我需要将每种方法都视为关联吗?
例如,这就是我渴望加载帐户本身的方式,当我调用此方法时是否也需要做类似的事情?
field :account,
AccountType,
null: true,
resolve: lambda { |obj, _args, _ctx|
BatchLoader::GraphQL.for(obj.account_id).batch do |account_ids, loader|
Account.where(id: account_ids).each { |account| loader.call(account.id, account) }
end
}
另外,如果我们做这样的事情,它会调用帐户两次吗?
calendarAppts {
appointmentTime
account {
id
name
}
}
【问题讨论】:
标签: ruby-on-rails graphql lazy-loading graphql-ruby