module Jennifer::QueryBuilder::EagerLoading

Overview

Includes methods required for associations eager loading.

Eager loading is a way to find objects of a certain class and a number of named associations. It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100 posts that each need to display their author triggers 101 database queries. Through the use of eager loading, the number of queries will be reduced from 101 to 2.

Direct including types

Defined in:

jennifer/query_builder/eager_loading.cr

Instance Method Summary

Instance Method Detail

def _select_fields : Array(Criteria) #

[View source]
def eager_load(*names, **deep_relations) #

Adds to select statement given relations (with corresponding LEFT OUTER JOIN) and loads them from results.

Contact.all.eager_load(:addresses)
# SELECT contacts.*, addresses.*
# FROM users
# LEFT JOIN addresses ON addresses.contact_id = contacts.id

You can specify nested relationships same way as in #includes:

Contact.all.includes(:addresses, friends: %i(addresses followers))

[View source]
def includes(*names, **deep_relations) #

Specify relationships to be included in the result set.

All specified relationships are loaded in a separate queries.

Contact.all.includes(:addresses)
Contact.all.includes(:addresses, friends: %i(addresses followers))

[View source]
abstract def multi_query_relation_tree #

[View source]
abstract def nested_relation_tree : NestedRelationTree #

[View source]
def preload(*names, **deep_relations) #

Alias for includes.


[View source]
def with_relation(names : Array) #

Mark recently added join to be used to retrieve for relations given in names.

This allows to specify custom JOIN and load results into specified relation.

Contact.all.join(Address) { and(Address._contact_id == Contact._id, Address._main) }.with_relation([:addresses])

[View source]
def with_relation(*names) #

Mark recently added join to be used to retrieve for relations given in names.

This allows to specify custom JOIN and load results into specified relation.

Contact.all.join(Address) { and(Address._contact_id == Contact._id, Address._main) }.with_relation(:addresses)

[View source]