1

I have the following models in my application:

class Order < Sequel::Model
    many_to_one(:client, class: 'Client', key: :client_id)
end

class Client < Sequel::Model
    one_to_many(:images, class: 'Image', key: :client_id, eager: :file)
end

class Image < Sequel::Model
    many_to_one(:file, class: 'File', key: :file_id, eager: :namespace)
end

class File < Sequel::Model
    many_to_one(:namespace, class: 'Namespace', key: :namespace_id)
end

class Namespace < Sequel::Model
end

I can fetch all Orders for all Clients with account_id=1 using eager_graph (eager_graph because the search column is in the client table):

orders = Order.eager_graph(:client).where(account_id: 1)

What is the best strategy to eager load all this entities? If I change it to .eager_graph(client: :images) the result will be a big query with a lot of joins.

Is it possible to have a separate query for every nested associations, like it was used only the .eager method?

I trying to fine tune this because of performance issues.
Thanks in advance.

Everton
  • 13
  • 3

1 Answers1

1

Sequel doesn't currently support mixing eager and eager_graph in that way. You could do:

Order.eager(:client=>{proc{|ds| ds.where(:account_id=>1)}=>:images}).all.
  select{|order| order.client}

But that may not be very efficient if most orders do not have that client. You may be better off doing:

clients = Client.where(:account_id=>1).eager(:orders, :images)
clients.flat_map(&:orders)
Jeremy Evans
  • 11,959
  • 27
  • 26
  • This worked, the number of queries was what i expected but i cannot paginate the orders using limit/offset. The eager is loading all orders for all clients and i think limiting on the ruby side is not efficient. Thanks for the help anyway, i appreciate your work – Everton Jul 27 '18 at 17:05
  • 1
    Sequel's master branch now supports what you want via the eager_graph_eager plugin: https://github.com/jeremyevans/sequel/commit/7a19a1617847ec9be12bac5104cf01bda102ff78 – Jeremy Evans Aug 03 '18 at 21:44