Presently, the Marten ORM allows to "join" related records that are targeted by a many_to_one or one_to_one relationship by using the #join query set method. When using #join, the specified relationships are followed and each record returned by the considered query set has the corresponding related objects already selected and populated. Using #join can result in performance improvements and can help reduce the number of SQL queries since related records are retrieved by creating an SQL join and by including their fields in the main SELECT statement.
This does not work for other types of relationships though, such as many_to_many relationships. To palliate this, let's introduce a new #prefetch query set method that will allow to "prefetch" the specified relationships. This method should do a separate lookup for each of the specified relationships and should do the "joining" part in Crystal.
The envisioned API is as follows:
article_1 = Article.filter(published: true)
puts article_1.comments.to_a # DB hit to retrieve the associated comment records
article_2 = Article.prefetch(:comments).filter(published: true)
puts article_2.comments.to_a # No additional DB hit
Description
Presently, the Marten ORM allows to "join" related records that are targeted by a
many_to_one
orone_to_one
relationship by using the#join
query set method. When using#join
, the specified relationships are followed and each record returned by the considered query set has the corresponding related objects already selected and populated. Using#join
can result in performance improvements and can help reduce the number of SQL queries since related records are retrieved by creating an SQL join and by including their fields in the main SELECT statement.This does not work for other types of relationships though, such as
many_to_many
relationships. To palliate this, let's introduce a new#prefetch
query set method that will allow to "prefetch" the specified relationships. This method should do a separate lookup for each of the specified relationships and should do the "joining" part in Crystal.The envisioned API is as follows: