Collections
Relations
Overview
Section titled “Overview”Relations define how collections are connected at the database level. They enable Rebase to:
- Render relation picker fields in entity forms
- Resolve related entities when displaying previews
- Generate foreign key constraints in the Drizzle schema
- Support cascade delete/update behaviors
Relations can be defined either inline within the property, or explicitly in the relations array of a collection:
1. Inline Relations (Recommended)
Section titled “1. Inline Relations (Recommended)”Declare the link on the property, nested under relation. Pick the kind and
the type offers exactly the fields that kind needs.
import { defineCollection } from "@rebasepro/cms-types";const postsCollection = defineCollection({ slug: "posts", name: "Posts", table: "posts", properties: { title: { type: "string", name: "Title" }, content: { type: "string", name: "Content", admin: { multiline: true } }, author: { type: "relation", name: "Author", relation: { kind: "belongsTo", target: () => usersCollection } } }});2. Explicit Relations Array
Section titled “2. Explicit Relations Array”For a link with no property of its own — nothing to name it by in the form or in
a table column — declare it in relations:
import { defineCollection } from "@rebasepro/cms-types";const usersCollection = defineCollection({ slug: "users", name: "Users", table: "users", properties: { name: { type: "string", name: "Name" } }, relations: [ { kind: "hasMany", relationName: "posts", target: () => postsCollection } ]});The five kinds
Section titled “The five kinds”A relation is one of five kinds. The kind decides where the key lives, whether one row or many come back, and what a write through it may touch.
| Kind | The key lives | Returns | Notes |
|---|---|---|---|
belongsTo |
on this table | one | localKey, defaults to <relationName>_id |
hasOne |
on the target’s table | one | foreignKeyOnTarget, defaults to the singular of this collection plus _id (users → user_id) |
hasMany |
on the target’s table | many | children belong to this parent alone |
manyToMany |
in a junction table | many | rows are shared; you own the link |
via |
an explicit joinPath |
either | writable when single-hop, read-only otherwise; state cardinality yourself |
Every field is optional except kind and target (and, on via, cardinality
and joinPath) — the rest is derived.
belongsTo — the key is on this table
Section titled “belongsTo — the key is on this table”author: { type: "relation", name: "Author", relation: { kind: "belongsTo", target: () => usersCollection }}// → posts.author_idThe column is
indexed for you: Postgres indexes the key a foreign key points at, never the
column holding it, so without one every hasMany include and nested listing
from the other side scans this table. index: false keeps the constraint and
drops the index — see Foreign keys are indexed for you
for when that is worth it, and for when Rebase skips it on its own because
another index already serves the column.
hasMany / hasOne — the key is on theirs
Section titled “hasMany / hasOne — the key is on theirs”relations: [ { kind: "hasMany", relationName: "posts", target: () => postsCollection }]// → reads posts.user_idhasOne is the same link with at most one row on the far side.
Joining on a natural key
Section titled “Joining on a natural key”By default the target’s foreign key holds the source row’s id. When the two
sides are joined on something else — an external identity id, a SKU, a tenant
slug — name that column with sourceKey:
relations: [ { kind: "hasMany", relationName: "applications", target: () => applicationsCollection, sourceKey: "auth_user_id", // column on THIS table foreignKeyOnTarget: "auth_user_id" // column on the TARGET's table }]// → reads applications.auth_user_id = talents.auth_user_idsourceKey is the mirror of localKey on belongsTo: that one names the
column this side reads from, this one names the column the other side points
at. Without it a link like the above is not expressible as hasMany at all
and has to drop to via, which is read-only for
a chain like this one.
The column must be unique. A link that addresses more than one source row cannot say which one a related row belongs to, and Postgres will not accept a foreign key against a non-unique column either. Rebase checks this at read time and refuses rather than picking one.
A parent whose sourceKey is NULL reaches no rows, and writing through the
relation is an error — there is nothing for the related rows to point at.
manyToMany — through a junction
Section titled “manyToMany — through a junction”tags: { type: "relation", name: "Tags", relation: { kind: "manyToMany", target: () => tagsCollection }}// → junction `posts_tags` (both table names, sorted), columns post_id / tag_idBoth sides declare their own, and each writes through from its own point of
view — sourceColumn always names this collection:
// on posts{ kind: "manyToMany", relationName: "tags", target: () => tagsCollection, through: { table: "posts_tags", sourceColumn: "post_id", targetColumn: "tag_id" } }
// on tags{ kind: "manyToMany", relationName: "posts", target: () => postsCollection, through: { table: "posts_tags", sourceColumn: "tag_id", targetColumn: "post_id" } }via — an explicit join chain
Section titled “via — an explicit join chain”For links the four shapes above cannot express: multi-hop paths, composite keys, or a join whose condition is not a plain foreign key.
A single-hop chain is writable through a create or update, the way the kind it stands in for is written:
- a to-one chain of one step — the target row holds the key, so
{ badge: "b-1" }points that row’s column at this one, andnullunlinks it, as ahasOnewrite does; - a to-many chain of two steps through one table between the ends — that
table holds the links, so
{ tags: ["t-1", "t-2"] }sets them as its rows, as amanyToManywrite does (aviacarries no_pivot).
Anything longer is read-only: Rebase will not infer how to write through an
arbitrary chain. A create or update naming one is refused with
400 RELATION_NOT_WRITABLE, and the admin form shows the field without a picker.
A nested write (PATCH users/1/permissions/3) through any via is refused the
same way.
{ kind: "via", relationName: "permissions", target: () => permissionsCollection, cardinality: "many", joinPath: [ { table: "user_roles", on: { from: "id", to: "user_id" } }, { table: "role_permissions", on: { from: "role_id", to: "role_id" } }, { table: "permissions", on: { from: "permission_id", to: "id" } } ]}Relation Properties
Section titled “Relation Properties”To render a relation field in a form, add a property with type: "relation":
properties: { author: { type: "relation", name: "Author", relation: { kind: "belongsTo", target: () => usersCollection }, // Which control draws it is presentation, so it goes in the admin block: // "select" (dropdown) or "dialog" (full picker). admin: { widget: "select" } }}When rendering a preview (like in a table cell or a reference chip), Rebase handles hydration automatically.
To-one gets a picker, many gets a tab
Section titled “To-one gets a picker, many gets a tab”The cardinality decides the surface, and only one surface is used:
belongsTo/hasOne— one row, so the property is a foreign key the author edits. It renders as the picker above.hasMany/manyToMany— many rows, so the entity view lists them as a tab of their own. The property is not rendered in the form: a collection’s children are a list, not a value the record holds, and selecting them from a dropdown is not something the form can meaningfully offer.
Declaring a many-relation as a property is still worth doing — it is what names the tab, and what gives the relation a column in the collection table, which the list fetch hydrates so the child rows show up as chips on the row. Only the form field is dropped.
In the table, a relation with a property of its own gets one column: its own.
Every tab also has a jump-to-tab button column, but for a property-declared
relation that button repeated the same heading beside a column already showing
the children, so it is dropped. Hide the relation’s column
(admin: { hideFromCollection: true }) and the button comes back, so the
relation never falls out of the table entirely.
Hiding the column does not stop the fetch. The collection’s list read embeds
every relation a property declares, hidden or not, so code that reads list
rows — additionalFields, display resolvers, entity actions, collection
actions through tableController.rows, plugin slots — finds the related rows
there, nested under the relation’s name as REST’s include returns them, beside
the foreign-key column. A browserCallbacks.afterRead is handed the same row. A relation declared only in the collection’s relations
array, with no property, is not embedded in the list; its rows load when its
tab opens.
If you want the inline picker anyway, ask for it:
properties: { tags: { type: "relation", name: "Tags", relation: { kind: "manyToMany", target: () => tagsCollection }, admin: { renderInForm: true } // off by default; the tab is the default treatment }}Multi-Hop Joins
Section titled “Multi-Hop Joins”For relationships that traverse multiple tables, use kind: "via" with a joinPath.
A chain longer than one link is read-only: Rebase will not infer how to write
through an arbitrary chain (see via for the
single-hop chains it does write).
// Users → Permissions through Rolesrelations: [ { kind: "via", relationName: "permissions", target: () => permissionsCollection, cardinality: "many", joinPath: [ { table: "user_roles", on: { from: "id", to: "user_id" } }, { table: "roles", on: { from: "role_id", to: "id" } }, { table: "role_permissions", on: { from: "id", to: "role_id" } }, { table: "permissions", on: { from: "permission_id", to: "id" } } ] }]Composite Key Joins
Section titled “Composite Key Joins”joinPath: [ { table: "customers", on: { from: ["company_code", "region_id"], // Multiple columns to: ["code", "region_id"] } }]Matching either of two columns
Section titled “Matching either of two columns”A list in on joins a row meeting any one condition — a link kept in a or b. It is read-only.
joinPath: [{ table: "friendships", on: [{ from: "id", to: "a" }, { from: "id", to: "b" }] }]Adding a second step to people (on: [{ from: "a", to: "id" }, { from: "b", to: "id" }]) also matches the parent’s own column, so each person comes back as their own friend: list the friendship rows, or filter the person out.
Cascade Rules
Section titled “Cascade Rules”Control what happens when related entities are updated or deleted:
relations: [ { kind: "belongsTo", relationName: "author", target: () => usersCollection, localKey: "author_id", onDelete: "cascade", // Delete posts when user is deleted onUpdate: "cascade" // Update FK when user ID changes }]| Action | Behavior |
|---|---|
"cascade" |
Propagate the change to related rows |
"restrict" |
Prevent the operation if related rows exist |
"no action" |
Same as restrict (defer to constraint check) |
"set null" |
Set the FK column to NULL |
"set default" |
Set the FK column to its default value |
What you get when you say nothing
Section titled “What you get when you say nothing”onDelete is optional, so most relations never name one. The default depends on
whether the relation is required:
| Relation | Default onDelete |
|---|---|
belongsTo, optional |
"set null" — the pointer is emptied |
belongsTo, validation: { required: true } |
"restrict" — the parent delete fails |
manyToMany (junction rows) |
"cascade" — the link goes, the target stays |
A required relation is not a cascade. required says a child cannot exist
without a parent; it does not say deleting the parent should destroy the child.
Those are different claims, and only one of them removes rows you did not name.
So the default fails the delete and names the constraint, and "cascade" is
something you ask for:
{ kind: "belongsTo", relationName: "order", target: () => ordersCollection, // A line item is meaningless without its order — say so. onDelete: "cascade"}onUpdate has no default: with nothing set, Postgres applies NO ACTION. Set
"cascade" when the target’s key is something a person can edit — a slug, a SKU
— so the pointers follow it.
Fetching Relations in the SDK
Section titled “Fetching Relations in the SDK”When querying data through the Rebase typed SDK, relations are not included by default. Use the include() method to request related entities alongside the primary data.
Include specific relations
Section titled “Include specific relations”const { data } = await client.data.articles .include("author", "categories") .find();Include all relations
Section titled “Include all relations”const { data } = await client.data.articles .include("*") .find();Using params syntax
Section titled “Using params syntax”const { data } = await client.data.articles.find({ include: ["author", "categories"]});Response structure
Section titled “Response structure”When included, the response contains both the scalar foreign key and the hydrated relation object:
const { data } = await client.data .collection<{ id: string; authorId: string; author?: { name: string } }>("articles") .include("author") .find();
// The SDK returns flat rows — there is no `.values` wrapper. (`Entity`, with// `id`/`path`/`values`, is an admin-UI view model, not what the client hands back.)for (const article of data) { // Scalar FK — always present article.authorId; // "uuid-1234"
// Hydrated relation — only present when included article.author?.name; // "Jane Doe"}The relation names passed to
include()must match the relation’s name: therelationNameof an entry in the collection’srelationsarray, or the key of the property that declares it inline.
For the full query builder reference (filtering, sorting, pagination, real-time), see the typed SDK documentation.
Relations in the admin panel
Section titled “Relations in the admin panel”Every to-many relation (hasMany, manyToMany, or a to-many via) becomes a tab under a record in the admin panel, addressed by the relation’s name. Relations in the admin panel covers the paths, what a tab creates, links, unlinks or deletes, the same rules over REST, and what does not become a tab.
Full Relation Interface
Section titled “Full Relation Interface”Relation is a closed union — one member per kind, each carrying only the
fields that kind has. There is no combination of fields that describes two
different links, and no field you can set that the kind does not use.
type Relation = | BelongsToRelation | HasOneRelation | HasManyRelation | ManyToManyRelation | ViaRelation;
interface RelationBase { relationName?: string; // defaults to the property key, then the target's slug target: () => CollectionConfig; onUpdate?: OnAction; onDelete?: OnAction; overrides?: Partial<CollectionConfig>; // applied when rendered as a tab}// `required` is not here. It is `validation: { required: true }` on the// property that declares the relation, the same key every other field uses.
interface BelongsToRelation extends RelationBase { kind: "belongsTo"; localKey?: string; // column on THIS table index?: boolean; // btree on localKey; defaults to true}
interface HasOneRelation extends RelationBase { kind: "hasOne"; foreignKeyOnTarget?: string; // column on the TARGET's table sourceKey?: string; // column on THIS table; defaults to the primary key}
interface HasManyRelation extends RelationBase { kind: "hasMany"; foreignKeyOnTarget?: string; // column on the TARGET's table sourceKey?: string; // column on THIS table; defaults to the primary key}
interface ManyToManyRelation extends RelationBase { kind: "manyToMany"; through?: { table?: string; sourceColumn?: string; targetColumn?: string; properties?: Properties; // extra columns on the junction row, served under `_pivot` };}
interface ViaRelation extends RelationBase { kind: "via"; cardinality: "one" | "many"; // a join chain cannot imply it joinPath: JoinStep[];}The resolved form
Section titled “The resolved form”What you write above is the authoring shape. Internally Rebase works with
ResolvedRelation: the same link with every default filled in and nothing
optional, plus cardinality, targetSlug, and two flags — writable (false
only for a multi-hop via or one with a step matching any of several conditions) and shared (true when the target rows belong to other parents
too, so a removal unlinks rather than deletes).
sourceKey is the one exception to “nothing optional”: its default is the
source’s primary key, and resolving that needs the driver’s schema, which
resolution does not have. undefined there means “the primary key” and nothing
else.
You never write a ResolvedRelation. On a relation property, relation is
yours and resolvedRelation is the filled-in one, stamped during
normalization.
Next Steps
Section titled “Next Steps”- Security Rules — Row Level Security
- Properties — Property types reference