Mainstay GitHub
All docs

Relations and depth

Entries pointing at each other, how far a read follows them, and what a missing target reads as.

A relation is an entry pointing at others, stored as their plain ids with no foreign key. The property says whether it holds one or a list.

Declare one

app/Content/Article.php
#[Relation(to: Person::class)]
public ?Person $author;

#[Relation(to: Article::class)]
public array $related;

#[Relation(to: [Page::class, Doc::class])]
public array $reading;

One type in to: stores the id: one in a column a where can filter on, a list as a JSON list of ids. Several store each as its type and id, since an id alone does not say which table it is in. For one of several types, type the property as a union of them. A list holds none rather than null.

Depth

A read follows relations to a depth, 1 by default: the entries a relation points at are loaded, and their own relations hold references. Ask for more where a page needs it:

$article = Mainstay::findById(Article::class, $id, depth: 2);

Depth 0 loads no related entries past the entry itself, which is right for a list that only prints titles. Images load at every depth. Every target is read through the same query every read starts from, so the site, the locale, the trash and Gate apply to it as to anything else read. A read loads each type's targets in one query, whatever the number of entries pointing at them.

Missing targets

A target that was not loaded is still an instance of its type, marked missing and holding its id. That happens when depth ran out, or the target is in the trash, gone, not written in the locale read, or of a type the reader may not read. A view asks before it links:

resources/views/article.blade.php
@foreach (collect($entry->related)->reject->missing as $article)
    <a href="{{ $article->url() }}">{{ $article->title }}</a>
@endforeach

Written back as it was read, a missing target keeps its place, so an entry saved while its target is in the trash still points at it when it comes back. A reference to a type the field no longer names is dropped from the next read and save.

Filtering on a relation

A relation of one type to one entry is a column, and a where takes the id:

Mainstay::find(Article::class, where: ['author' => $person->id]);

For a list of terms and the entries holding one, use a taxonomy: see Tags and taxonomies.