Relationships

Write relationships in schema code, on a column or on a line of their own, and say how many rows are on each side.

A relationship makes a column point at another table's key. You can write it on the column, or on a line of its own.

Write a relationship

On the column that holds the reference, add ref: to its settings:

Table orders {
  id integer [pk, increment]
  customer_id integer [not null, ref: > customers.id]
}

Or write it on a line of its own, outside the tables, starting with Ref::

Ref: orders.customer_id > customers.id

Both say the same thing.

The operators

The operator between the two columns says how many rows are on each side:

OperatorKindExample
>Many to oneorders.customer_id > customers.id: many orders, one customer.
<One to manycustomers.id < orders.customer_id: the same, written from the other side.
-One to oneprofiles.user_id - users.id: one profile per user. Make profiles.user_id unique.
<>Many to manyposts.id <> tags.id. Better as a junction table with a foreign key to each side. The checks warn about it.

Names, actions and composite keys

A Ref: line can do more than a ref: setting:

Ref fk_orders_customer: orders.customer_id > customers.id [delete: cascade, update: no action]
Ref: order_lines.(order_id, line_no) > order_rows.(order_id, line_no)
  • A name after Ref is the foreign key's name in SQL.
  • delete: and update: say what the database does to these rows when the row they point at is deleted, or its key changes. Each takes cascade, restrict, set null, set default or no action.
  • Columns in brackets, table.(a, b), relate a composite key. Both sides need the same number of columns.

Several relationships can share one block. Write Ref { … }, with one relationship per line inside.

Rules

A column can point at its own table, such as a comment's parent_id at comments.id.

Two columns can only be related once.

On this page