# Relationships

- [Introduction](#introduction)
- [Declaring the relationships clients may load](#declaring-the-relationships-clients-may-load)
- [Loading relationships](#loading-relationships)
- [What a response contains](#what-a-response-contains)
- [The order of a list](#the-order-of-a-list)
- [Nested relationships](#nested-relationships)
- [Picking columns](#picking-columns)
- [Limiting lists with relatablePerPage](#limiting-lists-with-relatableperpage)
- [Who can see a relationship](#who-can-see-a-relationship)
- [Raw relationships and the model's JSON](#raw-relationships-and-the-models-json)
- [Many-to-many relationships clients can change](#many-to-many-relationships-clients-can-change)
- [Attach, detach and sync](#attach-detach-and-sync)
- [Who may attach, detach and sync](#who-may-attach-detach-and-sync)
- [Nested routes](#nested-routes)

## Introduction

A post has an author and comments. With `?related=`, a client gets them in the same response as the post, instead of making one request per post:

```
GET /api/restify/posts?related=user,comments
```

Restify loads only the relationships the repository lists. It loads each one with one query for the whole page, as the framework's `with` does, so a list of 15 posts with their authors runs two queries, not sixteen.

The request and the response are the same as Restify for PHP's, so a client of a PHP application keeps working.

## Declaring the relationships clients may load

First declare the relationships on the model, as the framework's [model relationships](https://github.com/laravel/rust-framework/blob/0.x/docs/model-relationships.md) guide shows:

```rust
#[model]
pub struct Post {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
    // ...

    #[belongs_to]
    pub user: BelongsTo<User>,
    #[has_many]
    pub comments: HasMany<Comment>,
    #[belongs_to_many]
    pub tags: BelongsToMany<Tag, PostTag>,
}
```

Then list the ones clients may load in the repository's `related` method:

```rust
use restify::{Related, Repository};

impl Repository for PostRepository {
    // ...

    fn related() -> Vec<Related<Post>> {
        vec![
            Related::through::<UserRepository>(Post::user, |post| &post.user),
            Related::through::<CommentRepository>(Post::comments, |post| &post.comments),
            Related::raw(Post::tags),
        ]
    }
}
```

There are two ways to show a relationship:

| Declaration | Shows each related model as | Restify for PHP |
| --- | --- | --- |
| `Related::through::<UserRepository>(Post::user, \|post\| &post.user)` | A resource of the related repository: its list fields, its policy, its own relationships | `BelongsTo::make('user', UserRepository::class)`, `HasMany`, `HasOne`, `BelongsToMany` |
| `Related::raw(Post::tags)` | The related model's own JSON, as its `Serialize` writes it | A string in `related()`, such as `'tags'` |

Prefer `through`: it shows only what the related repository shows, to whom it shows it. `through` takes the relationship and a closure that returns the model's field for it, because the framework has no other way to read a loaded relationship. Every kind of relationship works with both, except `#[morph_to]`.

A client names a relationship by its field's name: `user`, `comments`, `tags`. A repository without a `related` method lets clients load nothing.

## Loading relationships

| Request | Loads |
| --- | --- |
| `GET /api/restify/posts?related=user` | Each post's author |
| `GET /api/restify/posts?related=user,comments` | Each post's author and comments |
| `GET /api/restify/posts/1?related=comments` | One post's comments |
| `GET /api/restify/posts/1?include=comments` | The same: `include` is another name for `related` |

- When a request sends both `related` and `include`, only `related` is read.
- A name the repository doesn't list is ignored, as Restify for PHP ignores it. The request still answers `200`.
- `?related=` works with every other list parameter, such as `?search=`, filters, `?sort=` and `?page=`. Create, update and delete don't take it.

The `posts-index-tool` and `posts-show-tool` MCP tools take the same thing as an `include` argument, as in Restify for PHP: a comma-separated string, such as `"user,comments"`. The argument's description lists the names the repository allows, so an agent knows what it may ask for. An MCP tool leaves out a relationship whose repository doesn't set `const MCP`. See [MCP](mcp.md).

## What a response contains

Each loaded relationship goes under the resource's `relationships` key, named as the client asked for it. It is never in `attributes`.

```json
{
    "data": {
        "id": "1",
        "type": "posts",
        "attributes": { "user_id": 1, "title": "Laravel for Rust", "votes": 10 },
        "relationships": {
            "user": { "id": "1", "type": "users", "attributes": { "name": "Ada Admin", "is_admin": true } },
            "comments": [
                { "id": "1", "type": "comments", "attributes": { "post_id": 1, "body": "Great read" } }
            ],
            "tags": [
                { "id": 1, "name": "rust", "created_at": "2026-01-01T09:00:00.000000Z", "pivot": { "post_id": 1, "tag_id": 1, "position": 2 } }
            ]
        }
    }
}
```

- A `through` relationship shows each related model as a resource of the related repository: `id`, `type`, and the repository's **list** fields as `attributes`, even when the parent is shown on its own. A related resource has no `meta`.
- A `raw` relationship shows the related model's JSON. See [Raw relationships and the model's JSON](#raw-relationships-and-the-models-json).
- A belongs-to or has-one relationship is one object, or `null` when there is no related row.
- A has-many or belongs-to-many relationship is a list, empty when there are no related rows. See [The order of a list](#the-order-of-a-list).
- A resource has a `relationships` key only when the request loads at least one relationship.

## The order of a list

PHP loads a relationship without `ORDER BY`, so it shows the rows in whatever order the database reads them. On SQLite and MySQL that order follows the indexes. Restify sorts by the same columns, so every database, PostgreSQL included, shows what PHP shows:

| Relationship | Order |
| --- | --- |
| Has-many, has-one-of-many, through | The related models' keys |
| Many-to-many, when the join table has an index that starts with the parent's column, such as `unique(['post_id', 'tag_id'])` for a post's tags | That index's other columns (`tag_id`), then the join table's key |
| Many-to-many without such an index, such as a `label_task` with only an `id` | The join table's key: the order the rows were attached in |
| Many-to-many whose join table has neither | The related models' keys |

The first request that loads a many-to-many reads its join table's indexes once, and keeps the answer until the application stops. If a migration changes those indexes, restart the application.

## Nested relationships

A dot loads the related repository's own relationships into each related model:

```
GET /api/restify/posts/1?related=comments.user
```

Each comment then has its own `relationships` key with its author. The names after the dot are those the related repository lists: `comments.user` works because `CommentRepository::related` lists `user`. Nesting works only through `through`: on a `raw` relationship, such as `?related=post.user` on a comment, the part after the dot is ignored and the post is shown without its author.

Restify for PHP differs on one point. On a **list**, such as `GET /comments?related=post.user`, PHP does load the author and puts it inside the raw post's JSON. Restify for Rust can't: the framework loads a relationship only through its typed method, such as `Post::user`, never from a name read in the URL. To get nested relationships, show the relationship with `through`.

### How deep, and how many

A request may go at most 3 relationships deep, such as `posts.comments.user`, and name at most 20 relationships in all, counting each one inside another: `comments.user,tags` names three. A request that asks for more answers `422`, and the message names the limit:

```json
{
  "message": "`user.posts.user.posts` goes 4 relationships deep, and at most 3 are allowed. Ask for the deeper relationships in another request, starting from the related repository. The limit is `RESTIFY_RELATED_MAX_DEPTH`.",
  "errors": { "related": ["`user.posts.user.posts` goes 4 relationships deep, and at most 3 are allowed. ..."] }
}
```

The error names `include` when the client sent `include`. An MCP tool's `include` argument has the same limits.

| Setting | Environment variable | Default |
| --- | --- | --- |
| `related_max_depth` | `RESTIFY_RELATED_MAX_DEPTH` | `3` |
| `related_max_paths` | `RESTIFY_RELATED_MAX_PATHS` | `20` |

`0` turns a limit off. Restify for PHP has no limits. Without them, two repositories that relate to each other, such as users and posts, let one request load the same rows again at every level, so the answer grows with each level. Every recorded PHP request stays within these limits. A name the repository doesn't list still counts toward the total, even though it is ignored.

## Picking columns

`?related=user[name]` shows only the related resource's `name`. Separate several columns with `|`: `?related=comments[body|user_id]`. Columns combine with nesting: `?include=posts[id|title].comments[body]`.

- A related resource shows the fields whose column the client picked, and only those its repository shows. `comments[body|user_id]` shows `body` alone when the comments repository has no `user_id` field.
- When one record is shown on its own, a related resource has no `id` unless the client picked the key column, such as `posts[id|title]`. A list keeps the `id`. Restify for PHP does the same, because it selects only the picked columns from the database in the first case.
- A `raw` relationship ignores the columns and shows the whole model.

## Limiting lists with relatablePerPage

`?relatablePerPage=5` loads at most 5 related models of each `through` relationship that holds a list, for each record. `?relatablePerPage[posts.comments]=5` limits one path only.

- When one record is shown on its own, a list relationship is always limited, by default to the related repository's `RELATABLE_PER_PAGE`, which is 15. A many-to-many relationship declared with [`Related::many`](#many-to-many-relationships-clients-can-change) is the exception. It uses the default of the repository that shows it, as Restify for PHP's `BelongsToMany` field does. `TeamRepository` sets `RELATABLE_PER_PAGE = 2`, so `GET /teams/1?related=users` shows two members.
- A list of records limits its relationships only when the request sends `relatablePerPage`, or the configuration sets `max_per_page`. Otherwise it loads every related model, as Restify for PHP does, and a recorded PHP answer depends on it. In production, set `RESTIFY_MAX_PER_PAGE`: it caps the page and turns this limit on for lists too. See [Before you go to production](production.md).
- A value that isn't a positive number falls back to `RELATABLE_PER_PAGE`, and `max_per_page` caps it.
- A `raw` relationship is never limited.

```rust
impl Repository for CommentRepository {
    // ...
    const RELATABLE_PER_PAGE: u64 = 10;
}
```

To load fewer related models whatever the request says, such as only approved comments, declare a filtered relationship on the model, like `#[has_many(filter = Comment::approved.eq(true))]`, and list that one instead.

## Who can see a relationship

A `through` relationship asks the related repository, as Restify for PHP's relationship fields do:

- A request that the related repository's `Action::AllowRestify` refuses doesn't get the relationship at all: it is left out of `relationships`, as if not asked for.
- The related rows are only those the related repository's `Repository::query` lets the request reach, as on that repository's own endpoints. `query` gets `Action::Index` for a relationship that holds a list, and `Action::Show` for one that holds one model. A row that `query` hides is left out of a list, and a relationship that holds one model shows `null`. Restify for PHP doesn't apply the related repository's query here.
- A related model that the related repository refuses to show, with `Action::Show`, is left out of a list. For a relationship that holds one model, the whole request answers `403`.
- Each related resource shows the fields its repository shows to this request, so a field with `can_see(is_admin)` stays hidden from other users.
- The related rows go through the related repository's soft-delete scope. A model whose PHP version uses `SoftDeletes` should also filter its relationships, such as `#[has_many(filter = Post::deleted_at.is_null())]`, because Eloquent leaves trashed rows out of every relationship.

To let only some requests load a relationship, give it a gate. Other requests don't get it, as if they hadn't asked:

```rust
Related::through::<UserRepository>(Post::user, |post| &post.user).can_see(is_admin)
```

A `raw` relationship asks nobody: a client that may see the parent sees the related model's JSON.

## Raw relationships and the model's JSON

`Related::raw` shows what the related model's `Serialize` writes, and nothing else decides it. So:

- Mark the fields no client may see `#[serde(skip)]` on the model, as Laravel's `$hidden` does.
- A many-to-many relationship adds a `pivot` to each model, as Laravel does: the join table's two key columns, such as `post_id` and `tag_id`, and the columns of the join row, which the framework would write under `join`.
- To write the same JSON as a PHP application, give the model's fields `#[serde(serialize_with = "..")]`. The example app's `models/php.rs` writes timestamps as Eloquent does (`2026-01-02T09:00:00.000000Z`, through `restify::Property::wire`), a `decimal:2` column as `"4.50"`, and an uncast boolean as `0` or `1`.

## Many-to-many relationships clients can change

`Related::many` shows a many-to-many relationship the same way `through` does. It also lets clients add and remove related models, with the endpoints in the next section. It works with `#[belongs_to_many]`, `#[morph_to_many]` and `#[morphed_by_many]`. It is the Rust version of Restify for PHP's `BelongsToMany` and `MorphToMany` fields.

For example, a team has members, and each member has a role. The role is stored in the join table `team_user`:

```rust
#[model]
pub struct Team {
    pub id: i64,
    pub name: String,
    // ...

    #[belongs_to_many]
    pub users: BelongsToMany<User, TeamUser>,
    #[morph_to_many(Tagging::taggable)]
    pub tags: MorphToMany<Tag>,
}

/// A row of `team_user`: the member's role on the team.
#[join_row]
pub struct TeamUser {
    /// `owner` or `member`. The column's default is `member`.
    #[default]
    pub role: String,
}
```

The repository lists both relationships with `Related::many`:

```rust
use laravel::validation::Rule;
use restify::{Pivot, Related};

fn related() -> Vec<Related<Team>> {
    vec![
        Related::many::<UserRepository>(Team::users, |team| &team.users)
            .pivot(Pivot::new(TeamUser::role).rules([Rule::required(), Rule::one_of(["owner", "member"])])),
        Related::many::<TagRepository>(Team::tags, |team| &team.tags),
    ]
}
```

`pivot` names a column of the join row. It does two things:

- Each related resource shows the column under `pivots`, such as `"pivots": { "role": "owner" }`.
- An attach reads the column from the request and checks it with its rules. With `Rule::required()`, every attach must send it.

Things to know:

- To show a pivot, the field's type must name the join row, such as `BelongsToMany<User, TeamUser>`. If it doesn't, the application refuses to start and says why.
- A sync never writes pivot columns. So a join column that has to be filled, like `role`, needs `#[default]` on the join row, and a default in the database.
- `Related::many` on a relationship that isn't many-to-many doesn't compile. Use `through` for the others.

## Attach, detach and sync

| Request | What it does | Answer |
| --- | --- | --- |
| `POST /api/restify/teams/1/attach/users` with `{"users": [2, 3], "role": "member"}` | Adds users 2 and 3 to team 1, each with the role sent | `201` with the new join rows |
| `POST /api/restify/teams/1/detach/users` with `{"users": [2]}` | Removes user 2 from team 1 | `204` with no body |
| `POST /api/restify/teams/1/sync/users` with `{"users": [1, 3]}` | Makes users 1 and 3 the only members | `200` with `[]` |

The URL ends with the relationship's name, and the body sends the keys under that same name. One key on its own works too, such as `{"users": 3}`. A key may be a number or a string.

An attach answers with each new join row, as Restify for PHP does:

```json
{ "data": [ { "team_id": 2, "user_id": 3, "role": "member" } ] }
```

For a polymorphic relationship, each row also has the type column, such as `"taggable_type": "team"`.

What can go wrong:

| Answer | When |
| --- | --- |
| `404` | No team has the key in the URL, or no user has one of the keys sent. A detach also finds soft-deleted users. |
| `400` | The repository has no `Related::many` with that name. Or the request may not use the related repository, because its `Action::AllowRestify` refuses. Or the relationship's `can_see` refuses. |
| `422` | A key is neither a number nor a string, or a pivot breaks its rules. Or an attach names a user who is already a member, or names one user twice: the error is under the relationship's name, such as `{"users": ["User 3 is already attached to this Team. Leave it out, or detach it first."]}`, and nothing is written. |
| `403` | The team's repository refuses the change. See the next section. |

Restify for PHP inserts the join row of an attach without checking, so attaching a member again answers its database's error, a `500`, when the join table has a unique index, and adds a second row when it hasn't. Restify for Rust answers the `422` above instead, whether the table has the index or not. Keep the unique index anyway: two attaches at the same moment can both pass the check, and the index stops the second.

Two details match Restify for PHP on purpose:

- Detaching a user who isn't a member still answers `204`.
- A sync only writes keys. Members who stay keep their role. New members get the column's default.

## Who may attach, detach and sync

Each change asks the parent's repository in `authorize`, with the relationship's name:

| Request | Question asked | How often |
| --- | --- | --- |
| attach | `Action::Attach("users")` | Once for each user sent |
| detach | `Action::Detach("users")` | Once for each user sent |
| sync | `Action::Sync("users")` | Once, for all the users |

The model that `authorize` gets is the team. To see which users the change is about, call `restify::relating::<User>(request)`. During an attach or a detach, it holds one user. During a sync, it holds all of them.

The users are looked up through the related repository, here `UserRepository`, the same way its own show endpoint finds a row. That means its `Repository::query` is applied, for `Action::Show`. So a user that `query` hides counts as missing, just like an id that no user has.

The permission is asked about the users that were found before missing ids are reported. So when a request names a user it may not attach and an id that doesn't exist, it gets `403`, and doesn't learn which of its ids exist. Restify for PHP looks every id up first, so it answers `404` before it asks the policy. When no id was found at all, the answer is `404`, as in PHP. That `404` tells nothing hidden, because only users that `query` lets the request reach count as found.

This example lets any user add themselves to a team, while only an admin may add other people:

```rust
async fn authorize(action: Action, request: &Request, _team: Option<&Team>) -> laravel::Result<()> {
    let allowed = match action {
        Action::AllowRestify | Action::Index | Action::Show | Action::Store => true,
        Action::Attach("users") => {
            let user: User = request.user().await?.or_abort(401)?;
            let joins_alone = restify::relating::<User>(request)
                .iter()
                .all(|member| member.id == user.id);
            user.is_admin || joins_alone
        }
        Action::Update
        | Action::Delete
        | Action::Detach("users")
        | Action::Sync("users")
        | Action::Attach("tags")
        | Action::Detach("tags") => is_admin(request).await?,
        _ => false,
    };

    if allowed { Ok(()) } else { Err(laravel::abort(403)) }
}
```

A question that `authorize` doesn't handle reaches `_ => false`, so it is refused. Here, nobody may sync tags. Restify for PHP answers that case with "Missing method [syncTags] in your policy". Restify for Rust answers with its usual refusal.

## Nested routes

Every relationship shown with `through` or `many` also gets routes under its parent. The URL uses the related repository's name, such as `comments`:

| Request | What it does |
| --- | --- |
| `GET /api/restify/posts/1/comments` | Lists the comments of post 1. Search, filters, sorting and pages work as usual. |
| `GET /api/restify/posts/1/comments/2` | Shows comment 2, if it belongs to post 1 |
| `POST /api/restify/posts/1/comments` | Creates a comment on post 1. The posts repository must allow `Action::Update` on post 1. |
| `PUT`, `POST` or `PATCH /api/restify/posts/1/comments/2` | Changes comment 2, if it belongs to post 1 |
| `DELETE /api/restify/posts/1/comments/2` | Deletes comment 2, if it belongs to post 1 |

The comments repository does the work, with its own fields, rules and `authorize`. The middleware of both repositories run: the posts repository's because the route is its own, and the comments repository's before the operation. See [Where the middleware run](repositories.md#where-the-middleware-run). `?related=` is different: it runs no middleware of the related repository. The parent adds four rules:

- **Only the parent's rows exist.** A comment of another post answers `404`, as if it didn't exist.
- **The parent must be visible.** The posts repository must allow `Action::Show` on the post, or the request answers `403`.
- **A write changes the parent.** A create, an update or a delete also needs `Action::Update` on the post, or it answers `403`. This holds even when the comments repository allows the write: a user who may comment but may not edit the post can't use `POST /posts/1/comments`. If the comments input has a `post_id` field, such a user can create with `POST /api/restify/comments` instead.
- **A new record belongs to the parent.** Restify puts the post's key into the input as `post_id`, so the comments' own rules see it. If the request sends a different `post_id`, it answers `422` with "The post_id must match the parent in the URL.". A create answers `201`, and its `Location` header holds the new comment's own path, such as `/api/restify/comments/6`.

Creating through the parent works for `#[has_many]`, `#[has_one]`, `#[morph_many]` and `#[morph_one]`:

- Through a polymorphic relationship, such as `POST /teams/1/notes`, Restify also sets the type column.
- For a has-many relationship, the related model must declare the `#[belongs_to]` back to the parent. That's how Restify knows which column holds the parent's key.
- Through a many-to-many relationship, a create answers `400`. Use attach instead.

When the parent's repository doesn't show the relationship through a repository, the request answers `403` with "Eager field missing from the parent [posts] related fields.". The same happens when the request may not use the relationship. A `raw` relationship has no nested routes.

The nested routes and attach, detach and sync are HTTP endpoints only. They have no MCP tools, because Restify for PHP has none.
