exAspArk / batch-loader

:zap: Powerful tool for avoiding N+1 DB or HTTP queries
https://engineering.universe.com/batching-a-powerful-way-to-solve-n-1-queries-every-rubyist-should-know-24e20c6e7b94
MIT License
1.04k stars 52 forks source link

Loading across collections #77

Open ivanyv opened 3 years ago

ivanyv commented 3 years ago

Is something like this possible?

class Types::SubcategoryType < Types::BaseObject
  def records
    BatchLoader.for(object.category_id).batch do |category_ids, loader|
      records = Record.where(category_id: category_ids).group_by(&:subcategory_id)
      loader.call(object.subcategory_id, records[object.id])
    end
  end
end

The goal is to load all records across all subcategories of a category at once. Currently the example above will return null because the batch call uses the category_id as the key, but on the loader call I'm using a subcategory_id.