Relations
relations lists every relation the resource may use. It does two separate jobs:
- Field paths. Every column reachable through these relations becomes a valid path for sorting, filters, search and facets:
customer.name,orderLines.quantity,orderLines.product.category. - Loading. When no load profile is set, these relations are loaded with each row.
import { engine } from "./engine";
engine.defineResource("orders", {
relations: {
customer: true,
orderLines: {
with: {
product: true,
},
},
},
});
With this declaration, each row has customer and orderLines[].product, and the row loading call is:
db.query.orders.findMany({ with: { customer: true, orderLines: { with: { product: true } } } });
A path that isn't reachable through relations is rejected before any SQL runs, and is a type error in your editor.
Load profiles
Lists usually need less than detail pages. Declare named subsets in hydration.profiles and pick a default per read method:
import { engine } from "./engine";
engine.defineResource("orders", {
relations: {
customer: true,
orderLines: { with: { product: true } },
},
hydration: {
profiles: {
list: { customer: true },
detail: {
customer: true,
orderLines: { with: { product: true } },
},
},
defaults: { query: "list", findById: "detail" },
},
});
Field paths still come from the full relations tree. A list row loaded with the list profile can be filtered by orderLines.product.category without loading orderLines.
Profile names and their relation subsets are inferred. An unknown profile name or a relation outside relations is a type error, and fails before a query runs in plain JavaScript.
For exact field selections, including columns, use views instead of profiles.
What each relation type costs
| Relation type | Joins | Notes |
|---|---|---|
Many-to-one or one-to-one (orders.customer) | One join | Cheap to sort, filter and facet on. |
One-to-many (orders.orderLines) | A join or an EXISTS subquery | Cost grows with the number of children per row. |
Many-to-many (products.tags via a junction) | Junction table plus target | Facets use count(distinct). Sorting is ambiguous: disable it until measured. |
A different plan for the page ids
Load profiles only change the returned rows. If selecting the page ids needs a specific join or index, replace that one step with strategy.ids:
import { engine } from "./engine";
engine.defineResource("orders", {
relations: {
customer: true,
orderLines: { with: { product: true } },
},
query: {},
strategy: {
ids: async ({ request, utils }) => {
return utils.executeIdsQuery({ request });
},
},
});
See Strategies.