martenframework / marten

The pragmatic web framework.
https://martenframework.com
MIT License
425 stars 24 forks source link

Avoid Unnecessary Database Query on Back Relations #265

Closed treagod closed 1 week ago

treagod commented 2 months ago

Description

When using back relations in Marten, unnecessary database queries are being executed when accessing the parent relation in a loop, Marten queries the database for each item, even though the parent object (e.g., list) has already been fetched. This results in inefficiencies and extra database load.

Example Scenario:

# many-to-one relation
List.get!(id: 1).items.each do |item|
  puts item.list # This invokes a database query for each item to fetch the list
end

In this scenario, item.list should reference the already-fetched list from List.get!(id: 1) without triggering additional queries.

Benefits