# Relations between schemas

**Problem.** An `Order` belongs to a `Customer`. Packs need to know the target, how many, and what happens on delete.

```ts
import {
  dryv,
  field,
  property,
  relation,
  schema,
  storage,
} from "@dryvcode/author";

const shared = dryv.group({ name: "shared" });
const values = shared.properties({
  Id: property.string.uuid(),
  Name: property.string(),
});

const sales = dryv.group({ name: "sales" });
const schemas = sales.schemas({
  Customer: schema({
    id: field(values.Id).system(),
    name: field(values.Name),
  }).facets({ storage: storage("customers").primaryKey("id") }),
});

sales.schemas({
  Order: schema({
    id: field(values.Id).system(),
    customerId: field(values.Id).relation({
      target: () => schemas.Customer.field("id"),
      cardinality: relation.manyToOne(),
      onDelete: relation.restrict(),
    }),
  }).facets({ storage: storage("orders").primaryKey("id") }),
});
```

## Point at a field, not a column

`schemas.Customer.field("id")` is a _semantic_ field reference. The compiler emits `{ $ref: <schema>, field: "id" }`, never a physical column path. A pack renders it as a foreign key, a reference, a join or a link, depending on the stack.

## Relate to an abstract base

```ts
const entities = sales.schemas({
  Entity: schema({ id: field(values.Id) }).abstract(),
});

sales.schemas({
  Membership: schema({
    ownerId: field(values.Id).relation({
      target: () => entities.Entity.field("id"),
      cardinality: relation.manyToOne(),
      onDelete: relation.restrict(),
    }),
  }),
});
```

Abstract schemas contribute shared fields and storage rules without being stored themselves.

Remember to compose every group into the app, including the shared one that owns the properties:

```ts
export default dryv.app({ name: "sales" }).groups(shared, sales);
```

## Choosing behaviour

| Option                 | Use it to say                                    |
| ---------------------- | ------------------------------------------------ |
| `relation.manyToOne()` | Many of this schema point to one target          |
| `relation.restrict()`  | Block deleting a target that is still referenced |

Check [Schemas](/authoring/vocabulary/schemas) for the full list of cardinalities and delete behaviours.
