Anvyr Docs
Documentation menu Anvyr Loom 1.x
Anvyr Loom

Version 1.x

← All documentation

GuideAnvyr Loom 1.xDeveloper

Model relationships

Load related records, avoid repeated lookups, and manage a many-to-many pivot.

On this page

Define both sides

Continue with the Note model in models and persistence. That model defines author() and tags() with explicit keys. Add the following classes as separate files under Notes/src/Models.

<?php

namespace Notes\Models;

use Anvyr\Loom\Database\Model;
use Anvyr\Loom\Database\Relations\HasMany;
use Anvyr\Loom\Database\Relations\HasOne;

class Author extends Model
{
    protected ?string $table = 'authors';
    protected array $fillable = ['name'];

    public function notes(): HasMany
    {
        return $this->hasMany(Note::class, 'author_id');
    }

    public function profile(): HasOne
    {
        return $this->hasOne(AuthorProfile::class, 'author_id');
    }
}
<?php

namespace Notes\Models;

use Anvyr\Loom\Database\Model;

class Tag extends Model
{
    protected ?string $table = 'tags';
    protected array $fillable = ['name'];
}

class AuthorProfile extends Model
{
    protected ?string $table = 'author_profiles';
    protected array $fillable = ['author_id', 'bio'];
}

The combined block shows two classes for brevity; put them in Tag.php and AuthorProfile.php for PSR-4 autoloading. The schema must include authors (id, name, timestamps), author_profiles (id, author_id, bio, timestamps), tags (id, name, timestamps), and note_tag (note_id, tag_id). Add a unique key for author_profiles.author_id and a composite unique key for the pivot pair if your data requires one profile and no duplicate attachments.

use Notes\Models\Author;
use Notes\Models\AuthorProfile;
use Notes\Models\Note;
use Notes\Models\Tag;

$author = Author::create(['name' => 'Ada']);
AuthorProfile::create(['author_id' => $author->getKey(), 'bio' => 'Writes field notes.']);
$note = Note::create(['title' => 'Relationships', 'author_id' => $author->getKey()]);

$name = $note->author->name;                 // Ada
$notes = $author->notes;                    // Collection<Note>
$profile = $author->profile;                // AuthorProfile or null

A relationship property loads results and remembers them on the model instance. Call the relationship method to obtain its relationship object, such as $note->tags() for pivot mutations. Refresh an already loaded relation with unsetRelation('tags') before reading the property again after a mutation.

Eager-load for a list

$notes = Note::query()->with(['author', 'tags'])->orderBy('id')->get();
foreach ($notes as $item) {
    $authorName = $item->author?->name;
}

with() accepts a relationship name or a list of names. Eager loading fetches related results for the set of parent models and matches them back, instead of triggering a separate lazy lookup for each row. Include the parent and relationship keys in custom projections.

Use direct relationship names here. Nested dot notation such as author.profile and callback-constrained eager loading are not exposed by this implementation of with().

Attach, synchronize, and detach tags

$tag = Tag::create(['name' => 'framework']);
$other = Tag::create(['name' => 'php']);
$note->tags()->attach([$tag->getKey(), $other->getKey()]);
$attached = $note->tags()->isAttached($tag->getKey()); // true

$changes = $note->tags()->sync([$tag->getKey()]);
// $changes has attached and detached ID lists.
$removed = $note->tags()->detach($tag->getKey());

sync() treats its IDs as the desired membership set and removes other attachments. toggle() returns attached/detached lists too. Use withPivot(['column']) to expose additional pivot columns and withTimestamps() only when the pivot table has the matching timestamp columns.

Key conventions and limits

Relation Explicit arguments after related class
hasOne, hasMany Foreign key, local key
belongsTo Foreign key, owner key
belongsToMany Pivot table, foreign pivot key, related pivot key, parent key, related key

Defaults infer foreign keys from model names and the many-to-many table from sorted model names. Explicit keys make the schema easier to follow when names differ. Defining a relation does not create foreign keys or enforce authorization.

Verified against HasRelationships, ModelBuilder, and BelongsToMany.

Continue readingQueries and transactions