Skip to content

Models: Relationships ​

Introduction ​

In Eloquent, relationships are methods (hasMany, belongsTo). In DotBlaze they are plain properties, EF Core navigation properties: a collection for "many" and a single model for "one". EF Core works out the relationship from the property types and the foreign key property, and DotBlaze applies Laravel's naming conventions to the tables and columns.

EloquentDotBlaze
hasMany(Post::class)public List<Post> Posts { get; set; } = [];
belongsTo(User::class)public long UserId { get; set; } and public User? User { get; set; }
hasOne(Profile::class)public Profile? Profile { get; set; }
belongsToMany(Tag::class)public List<Tag> Tags { get; set; } = []; on both sides

Defining Relationships ​

One to Many ​

A user has many posts. The parent gets a collection property:

csharp
public class User : Model<User>
{
    public long Id { get; set; }
    // ...
    public List<Post> Posts { get; set; } = [];
}

One to Many (Inverse) / Belongs To ​

The child has the foreign key property and, optionally, a property for the parent. UserId maps to the user_id column:

csharp
public class Post : Model<Post>
{
    public long Id { get; set; }
    public long UserId { get; set; }
    // ...
    public User? User { get; set; }
}

The matching migration column:

csharp
t.ForeignId("user_id").Constrained().CascadeOnDelete();

Make the foreign key long? when the relationship is optional.

One to One ​

A one-to-one relationship is a single navigation property on both sides, with the foreign key on the dependent side:

csharp
public class User : Model<User>
{
    public long Id { get; set; }
    public Profile? Profile { get; set; }
}

public class Profile : Model<Profile>
{
    public long Id { get; set; }
    public long UserId { get; set; }
    public User? User { get; set; }
}

Give the foreign key column a unique index in the migration (t.ForeignId("user_id").Unique().Constrained()).

Many to Many ​

Give both models a collection of the other:

csharp
public class Book : Model<Book>
{
    public long Id { get; set; }
    // ...
    public List<Tag> Tags { get; set; } = [];
}

public class Tag : Model<Tag>
{
    public long Id { get; set; }
    public string Name { get; set; } = "";
    public List<Book> Books { get; set; } = [];
}

The pivot table follows Laravel's convention: the two singular table names in alphabetical order, joined by _, with a {singular}_id column for each side. For books and tags that is book_tag with book_id and tag_id. You create it in a migration like any other table:

csharp
Schema.Create("book_tag", t =>
{
    t.ForeignId("book_id").Constrained().CascadeOnDelete();
    t.ForeignId("tag_id").Constrained().CascadeOnDelete();
    t.Primary("book_id", "tag_id");
});

Extra pivot columns can be declared on the navigation with [PivotColumn("Rank", typeof(int))]; [PivotTimestamps] maps nullable created_at/updated_at columns. Add those columns to the pivot migration too. Existing databases need an additive migration with defaults or nullable columns before deploying a model that declares them.

Non-Conventional Names ​

When the foreign key does not follow the {Navigation}Id naming, or a model has two relationships to the same model, use EF Core's standard data annotations from System.ComponentModel.DataAnnotations.Schema:

csharp
public class Post : Model<Post>
{
    public long Id { get; set; }

    public long WriterId { get; set; }
    [ForeignKey(nameof(WriterId))] public User? Writer { get; set; }
}

[InverseProperty] pairs up navigation properties when EF Core cannot tell which belong together.

Querying Relations ​

Relationships are ordinary properties, so to query "the posts of this user", query the related model by its foreign key:

csharp
var posts = await Post.Where(p => p.UserId == user.Id).OrderByDesc(p => p.Id).Get();

Querying Relationship Existence ​

Navigation properties can be used inside Where lambdas; EF Core turns them into SQL joins or subqueries. This replaces Eloquent's has and whereHas:

csharp
// Authors with at least one book
var authors = await Author.Where(a => a.Books.Any()).Get();

// Authors with a book over 20
var authors = await Author.Where(a => a.Books.Any(b => b.Price > 20)).Get();

// Books by active authors
var books = await Book.Where(b => b.Author!.IsActive).Get();

Relationship Aggregates ​

WithCount and WithSum select aggregates in the same SQL query as the models:

csharp
var authors = await Author.Query()
    .WithCount(a => a.Books)
    .WithSum(a => a.Books, b => b.Price)
    .Get();

authors.First()!.GetAttribute<int>("BooksCount");
authors.First()!.GetAttribute<decimal>("BooksSumPrice");

Pass alias: "Total" to choose another attribute name; aliases cannot replace declared model properties. Aggregates are available on Get, First, pagination, batches, and Cursor, and are included in JSON (booksCount, booksSumPrice). Related-model query filters remain active. These selectors use mapped EF navigations; arbitrary relation methods are queried explicitly.

Eager Loading ​

Navigation properties are empty until you load them. With loads relationships together with the query, so a list of posts with their authors takes one query instead of one per post:

csharp
var posts = await Post.With(p => p.User).OrderByDesc(p => p.Id).Paginate(10);

foreach (var post in posts.Items)
{
    Console.WriteLine(post.User?.Name);
}

Call With several times to load several relationships:

csharp
var book = await Book.With(b => b.Author).With(b => b.Tags).Where(b => b.Id == id).First();

Nested Eager Loading ​

Pass a dotted path of property names to load relationships of relationships:

csharp
var authors = await Author.With("Books.Tags").Get();

Lazy Eager Loading ​

Load loads a relationship on a model you already have, like Eloquent's $model->load(). It works for single models and collections, and returns the model:

csharp
public async Task<IActionResult> Show(Post post)
{
    await post.Load(p => p.User);
    return View(post);
}

await author.Load(a => a.Books);

Load takes one relationship per call; use With with a dotted path for nested ones.

No Lazy Loading ​

DotBlaze does not lazy load, by design: reading post.User never runs a query. An unloaded reference is null and an unloaded collection is empty. This keeps queries visible and avoids accidental N+1 problems.

NOTE

EF Core fills navigation properties with models already tracked in the same scope. If you loaded user 1 earlier in the request, post.User may already be set even without With. Do not rely on this; load what you use.

Set the foreign key and save the child:

csharp
var book = new Book { AuthorId = author.Id, Title = "DotBlaze in Action" };
await book.Save();

Keep foreign keys out of [Fillable] and set them directly, then mass-assign the rest:

csharp
var post = new Post { UserId = (long)Auth.Id()! };
await post.Update(new { request.Title, request.Body });

Many to Many Relationships ​

When you save a new model, related models added to its collections are saved with it, including the pivot rows:

csharp
var book = new Book { AuthorId = author.Id, Title = "T" };
book.Tags.Add(new Tag { Name = "one" });
book.Tags.Add(new Tag { Name = "two" });
await book.Save();   // inserts the book, two tags, and two book_tag rows

NOTE

To attach or detach on an existing model, add to or remove from its collection and call Save. New related models receive their own casts, events, and timestamps. If the parent's columns did not change, it fires only Saving/Saved and keeps its timestamps. Pivots declared with [PivotTimestamps] are stamped when their rows are written.

For writes that affect only the pivot, use ManyToMany:

csharp
var tags = book.ManyToMany(b => b.Tags);
await tags.Attach(tag.Id);
await tags.Detach(tag.Id);
await tags.Sync(new[] { first.Id, second.Id }); // replace the linked IDs
await tags.Detach();                          // remove every link for this book

Related IDs must exist and be visible through their global scopes. Attach is idempotent: a link already present is updated rather than duplicated. Sync applies removals and additions in one transaction. Each method returns the database's affected-row count; pivot writes do not save pending parent attributes or fire model events.

For extra fields:

csharp
[PivotColumn("Rank", typeof(int)), PivotTimestamps]
public List<Tag> Tags { get; set; } = [];
csharp
var tags = book.ManyToMany(b => b.Tags).WithPivot("Rank");
await tags.Attach(tag.Id, new { Rank = 3 });
await tags.UpdateExistingPivot(tag.Id, new { Rank = 4 });
var linked = await tags.Get(q => q.OrderBy(t => t.Name));
var rank = Convert.ToInt32(linked.First()!.Pivot["rank"]);

Get includes the foreign keys, requested columns, and configured timestamps under each related model's Pivot dictionary and JSON pivot field. It returns separate untracked instances so two parents can expose different pivot values for the same related record. Query() asynchronously returns a related-model query for further composition.

Writes refresh a mapped navigation that was already loaded, while retaining dirty parent columns. Save pending collection edits before using these helpers; mixing unsaved collection changes with direct pivot writes is refused. Pivot attributes cannot replace relationship keys or morph discriminators.

Through and One-of-Many Queries ​

Through relations are explicit queries built from the two foreign keys. For an author whose books have reviews:

csharp
var reviews = await author
    .HasManyThrough<Book, Review>(b => b.AuthorId, r => r.BookId)
    .Get();
var review = await author
    .HasOneThrough<Book, Review>(b => b.AuthorId, r => r.BookId)
    .First();

The intermediate and related models must share the parent's connection. Both models' global scopes apply. These helpers query relationships; inserting records through an intermediate model remains explicit.

On any model query, select one related row by its key or another value:

csharp
var latest = await Book.Where(b => b.AuthorId == author.Id).LatestOfMany().First();
var oldest = await Book.Where(b => b.AuthorId == author.Id).OldestOfMany().First();
var priciest = await Book.Where(b => b.AuthorId == author.Id).OfMany(b => b.Price).First();
var cheapest = await Book.Where(b => b.AuthorId == author.Id).OfMany(b => b.Price, maximum: false).First();

OfMany uses the primary key as a deterministic tie-breaker. These queries return at most one record.

Polymorphic Relationships ​

Register stable aliases in a provider's Boot; stored discriminator values resolve only through this map:

csharp
Model.MorphMap<Post>("post");
Model.MorphMap<Video>("video");

Suppose Comment declares CommentableType, CommentableId, and a fillable Body. The ID column must accommodate the referenced models' key types:

csharp
var comments = post.MorphMany<Comment>(c => c.CommentableType, c => c.CommentableId);
await comments.Create(new { Body = "Hello" });
var latest = await comments.LatestOfMany().First();
var owner = await Model.MorphTo(comment.CommentableType, comment.CommentableId);

comment.AssociateMorph(c => c.CommentableType, c => c.CommentableId, video);
await comment.Save();

MorphMany constrains both the ID and type, and its Create/find-or-create helpers set those fields after mass assignment. MorphOne has the same arguments and returns a query limited to one row. MorphTo returns the resolved model or null if it is missing; unknown aliases are rejected. Add an index on the type/ID pair, or a unique index for a one-to-one relation.

Polymorphic many-to-many uses an explicit pivot table:

csharp
var tags = post.MorphToMany<Tag>("taggables", "taggable_id", "tag_id", "taggable_type")
    .WithPivot("rank").WithTimestamps();
await tags.Attach(tag.Id, new { rank = 1 });
await tags.Sync(new[] { first.Id, second.Id });

var posts = await tag.MorphedByMany<Post>("taggables", "tag_id", "taggable_id", "taggable_type").Get();

Create the pivot table with a unique key on (taggable_type, taggable_id, tag_id), plus any extra columns and optional timestamps. Its helpers constrain every write by the parent key and morph type. Table and column arguments are application-defined identifiers, not request input.

Through and polymorphic helpers are explicit queries, not EF navigation properties: call Get/First on them. With/Load continue to handle mapped navigations. Changing an existing morph alias requires migrating the stored discriminator values.

Complete Example: Load a Post Author ​

The blog model and migration declare both UserId and the User navigation. Add this to the Blog test project:

csharp
// Blog.Tests/RelationshipTest.cs
using Blog.Models;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class RelationshipTest
{
    [Fact]
    public async Task Eager_loading_reads_the_author_in_a_fresh_scope()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        var author = await app.Run(() => User.Factory().Create());
        var id = await app.Run(async () =>
        {
            var post = new Post { UserId = author.Id, Title = "Related", Body = "Body" };
            await post.Save();
            return post.Id;
        });
        var loaded = await app.Run(() => Post.With(post => post.User).FindOrFail(id));
        Assert.NotNull(loaded.User);
        Assert.Equal(author.Id, loaded.User.Id);
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~RelationshipTest. Using a fresh scope avoids accidentally proving only EF's in-memory relationship fix-up. Add public List<Post> Posts { get; set; } = []; to the existing User model if you also need the inverse collection; loading one direction does not automatically query the other.