Avoiding N+1 queries when presenting a 2nd degree relationship in a collection

How do I avoid the ‘N+1 queries’ problem when I add a field which represents a 2nd degree relationship, in a collection?

Example:
My DB has 3 models: an item, a vendor, and a vendor category.
For example, a “Table” from “Ikea”, which is a “Furniture company”.

Item and Vendor has a one-to-many relationship, and so do Vendor and Vendor Category.

This means that every item has exactly one Vendor Category. In Forest Admin, I want to add a ‘Vendor Category’ column to the “Items” collection.

One way I found to implement this, was to add a smart field that fetches the correct Vendor Category from the DB, for every item. However, this results in N calls to the DB (where N is the number of items presented in a page).

Is there a way to present this column, that does not involve N+1 queries? Thanks!

Hello @Oded_Magger,

Thank you for your message.

This performance issue with SmartFields is known to us and has be very recently moved to our short term roadmap.

Meanwhile, I can offer two alternatives.

First, you can use updatable views (if using PostgreSQL). This will allow the join to be made DB side and remove the need for the smart field.
One thing though, only the fields from the “main” table of the view will be editable directly (I think “items” in your case).

The second one is to use the SmartCollection feature of Forest Admin.
This will require more code on your end, but won’t require any change in your database schema.

Hope this helps

2 Likes