martenframework/marten

Avoid Unnecessary Database Query on Back Relations

Closed this issue · 0 comments

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

  • Improved Performance: Reduces the number of redundant database queries, improving the performance of applications using Marten.
  • Resource Efficiency: Lowers the load on the database.
  • Developer Experience: Aligns with expected behavior, where related objects should efficiently reference each other without extra queries.