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.idBoth say the same thing.
The operators
The operator between the two columns says how many rows are on each side:
| Operator | Kind | Example |
|---|---|---|
> | Many to one | orders.customer_id > customers.id: many orders, one customer. |
< | One to many | customers.id < orders.customer_id: the same, written from the other side. |
- | One to one | profiles.user_id - users.id: one profile per user. Make profiles.user_id unique. |
<> | Many to many | posts.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
Refis the foreign key's name in SQL. delete:andupdate:say what the database does to these rows when the row they point at is deleted, or its key changes. Each takescascade,restrict,set null,set defaultorno 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.