dust

Database: Model Relationships

Introduction

Tables are often related to each other: a blog post has an author and many comments. Relationships let you declare these connections on your models once, then load, filter, and create related models without writing join queries by hand.

A relationship is a field on a model annotated with an attribute such as #[belongs_to] or #[has_many]. For example, this Post belongs to a user and has many comments:

rust
// src/models/post.rsuse dust::model::{BelongsTo, HasMany, model};use dust::time::Timestamp;use crate::models::{Comment, User};#[model]pub struct Post {    pub id: i64,    pub user_id: i64,    pub title: String,    #[default]    pub votes: i64,    pub published_at: Option<Timestamp>,    pub created_at: Timestamp,    pub updated_at: Timestamp,    #[belongs_to]    pub user: BelongsTo<User>,    #[has_many]    pub comments: HasMany<Comment>,}

Once a relationship is declared, you can eager-load it when querying the model:

rust
use dust::prelude::*;use crate::models::Post;pub async fn show(Params(id): Params<i64>) -> dust::Result<Json<Post>> {    let post = Post::query()        .with((Post::user, Post::comments))        .find_or_fail(id)        .await?;    Ok(Json(post))}

Relationships are never lazy-loaded behind the scenes. Load the relationships you need up front with with (or query them directly through methods such as post.comments()), preventing accidental N+1 queries by design.

Declaring relationships

Annotate a model field with the relationship attribute and its matching wrapper type (such as #[belongs_to] with BelongsTo<User> or #[has_many] with HasMany<Comment>). Relationship fields are not database columns, and queries return them unloaded by default until you request them through eager loading.

Relationship cheat sheet

Attribute Wrapper Points at Typical inverse
#[belongs_to] BelongsTo<T> A parent key stored on this table #[has_one] or #[has_many]
#[has_one] HasOne<T> One child whose foreign key names this model #[belongs_to]
#[has_many] HasMany<T> Many children whose foreign key names this model #[belongs_to]
#[belongs_to_many] BelongsToMany<T> Rows linked through a join table #[belongs_to_many]
#[has_one_through] HasOneThrough<T> One row reached through an intermediate model #[belongs_to] chains
#[has_many_through] HasManyThrough<T> Many rows reached through an intermediate model #[belongs_to] chains
#[morph_to] MorphTo<E> A parent of one of several types #[morph_one] or #[morph_many]
#[morph_one] MorphOne<T> One polymorphic child #[morph_to]
#[morph_many] MorphMany<T> Many polymorphic children #[morph_to]
#[morph_to_many] MorphToMany<T, J> Rows linked through a polymorphic join row #[morphed_by_many]
#[morphed_by_many] MorphedByMany<T> The other side of a polymorphic many-to-many #[morph_to_many]

A #[has_one] or #[belongs_to] that may find no row wraps its target in Option, as in HasOne<Option<Profile>>. A #[has_many] always yields zero or more rows, so its wrapper is not optional. latest_of_many and of_many(..) are options on #[has_one] and #[morph_one], not separate attributes.

Has one and has many

A #[has_many] relationship connects a parent model to any number of child records. For example, a user has many posts where each post's user_id column stores the user's primary key. By default, dust-framework expects the foreign key on the child table to match the parent struct's snake-case name plus _id (user_id for User, blog_post_id for BlogPost):

rust
// src/models/user.rsuse dust::auth::Authenticatable;use dust::model::{HasMany, model};use crate::models::Post;#[model]#[derive(Authenticatable)]pub struct User {    pub id: i64,    pub name: String,    pub email: String,    // Other fields...    #[has_many]    pub posts: HasMany<Post>,}

A #[has_one] relationship follows the same naming convention when at most one related row exists per parent, such as a Profile with a user_id column. Wrap the target type in Option (HasOne<Option<Profile>>) whenever a record may not exist, because loading a non-optional HasOne<Profile> fails if no profile is found:

rust
#[has_one]pub profile: HasOne<Option<Profile>>,

If the foreign key or parent key uses a non-default column name, override them with foreign_key and local_key. For example, this matches posts whose author_email column equals the user's email:

rust
#[has_many(foreign_key = "author_email", local_key = "email")]pub authored_posts: HasMany<Post>,

Belongs to

A #[belongs_to] relationship is the inverse of #[has_one] and #[has_many], linking a foreign key column on the current model to another model's primary key. By convention, dust-framework appends _id to the field name, so user reads user_id:

rust
use dust::model::{BelongsTo, model};use crate::models::User;#[model]pub struct Post {    pub id: i64,    pub user_id: i64,    pub editor_id: Option<i64>,    #[belongs_to]    pub user: BelongsTo<User>,    #[belongs_to]    pub editor: BelongsTo<Option<User>>,}

Use BelongsTo<Option<User>> whenever the foreign key is nullable (like editor_id above) or the referenced record might not exist, since eager loading a non-optional BelongsTo<User> returns an error if the parent row is missing.

If your table uses non-standard column names, specify them explicitly. foreign_key is the column on this model, and owner_key is the referenced column on the related model. Here, author matches the post's author_email column against the user's email column:

rust
#[belongs_to(foreign_key = "author_email", owner_key = "email")]pub author: BelongsTo<User>,

Belongs to many

Many-to-many relationships connect models in both directions through an intermediate join table. For example, a post may have many tags, and each tag may belong to many posts:

rust
// src/models/post.rsuse dust::model::{BelongsToMany, model};use crate::models::Tag;#[model]pub struct Post {    pub id: i64,    // ...    #[belongs_to_many]    pub tags: BelongsToMany<Tag>,}
rust
// src/models/tag.rsuse dust::model::model;#[model]pub struct Tag {    pub id: i64,    pub name: String,}

By default, dust-framework determines the join table name by joining both models' snake-case names in alphabetical order with an underscore (so Post and Tag use post_tag), and expects foreign key columns named after each model plus _id (post_id and tag_id).

Create the join table in a migration, adding a unique index on the pair of foreign keys so the same tag cannot be attached to a post twice:

rust
// database/migrations/2026_11_07_120000_create_post_tag_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("post_tag", |table| {            table.foreign_id("post_id").constrained().cascade_on_delete();            table.foreign_id("tag_id").constrained().cascade_on_delete();            table.unique(["post_id", "tag_id"]);        })        .await}

To customize the join table or column names, pass them as attribute arguments:

rust
#[belongs_to_many(    table = "role_user",    foreign_join_key = "member_id",    related_join_key = "role_id",)]pub roles: BelongsToMany<Role>,

Has one of many

When a model has many related rows, you often need easy access to a single standout record, such as a user's most recent order. Declare a #[has_one(latest_of_many)] relationship alongside the #[has_many] relationship:

rust
// src/models/user.rsuse dust::model::{HasMany, HasOne, model};use crate::models::Order;#[model]pub struct User {    pub id: i64,    // ...    #[has_many]    pub orders: HasMany<Order>,    #[has_one(latest_of_many)]    pub latest_order: HasOne<Option<Order>>,}

latest_of_many selects the order with the largest primary key, while oldest_of_many selects the smallest. Declare the field as HasOne<Option<Order>> unless every user is guaranteed to have an order.

To order by a timestamp or other column instead of the primary key, pass the column to latest_of_many or oldest_of_many:

rust
#[has_one(latest_of_many = Order::placed_at)]pub latest_order: HasOne<Option<Order>>,

To select a record by the largest or smallest value of a column, such as a user's largest order by price, use of_many with max or min:

rust
#[has_one(of_many(Order::price, max))]pub largest_order: HasOne<Option<Order>>,

Ties are broken by the larger primary key for max and latest_of_many, and by the smaller primary key for min and oldest_of_many. Rows where the ordering column is NULL are excluded. #[morph_one] and #[has_one_through] accept the same options, such as #[morph_one(Image::imageable, latest_of_many)].

A has-one-of-many relationship works like any other #[has_one] with with, with_count, and has_where. Conditions apply specifically to the single selected row, so this query finds users whose latest order is pending rather than users who have any pending order:

rust
use crate::models::{Order, User};let waiting = User::query()    .has_where(User::latest_order, Order::status.eq("pending"))    .with(User::latest_order)    .get()    .await?;

Constrained eager loads also apply after the row is chosen: User::latest_order.query(|orders| orders.filter(..)) picks the latest order first and loads it only if it satisfies the filter. If you want the latest order among rows matching a condition (such as the latest paid order), declare a filter on the relationship attribute so the filter runs before the selection.

Has one through and has many through

A through relationship reaches distant rows via an intermediate model. For example, suppose a project has many environments and each environment has many deployments. Even though deployments does not reference projects directly, a project can query all of its deployments through its environments:

rust
// src/models/project.rsuse dust::model::{HasMany, HasManyThrough, model};use crate::models::{Deployment, Environment};#[model]pub struct Project {    pub id: i64,    pub name: String,    #[has_many]    pub environments: HasMany<Environment>,    #[has_many_through(Project::environments, Environment::deployments)]    pub deployments: HasManyThrough<Deployment>,}
rust
// src/models/environment.rsuse dust::model::{HasMany, model};use crate::models::Deployment;#[model]pub struct Environment {    pub id: i64,    pub project_id: i64,    pub name: String,    #[has_many]    pub deployments: HasMany<Deployment>,}

#[has_many_through] references two existing relationships: the parent's relationship to the intermediate model, followed by the intermediate model's relationship to the target model. Both steps may be #[has_one], #[has_many], #[morph_one], or #[morph_many] (excluding has-one-of-many relationships). Because keys are inherited from those two relationships, through attributes take no key options.

#[has_one_through] follows the same pattern when at most one related row exists, such as reaching a car's owner through a mechanic's car:

rust
#[has_one]pub car: HasOne<Option<Car>>,#[has_one_through(Mechanic::car, Car::owner)]pub car_owner: HasOneThrough<Option<Owner>>,

To pick one of many rows through the intermediate model, such as a project's latest deployment across all environments, place the latest_of_many option directly on #[has_one_through] rather than referencing a latest_of_many relationship as the second step:

rust
#[has_one_through(    Project::environments,    Environment::deployments,    latest_of_many,)]pub latest_deployment: HasOneThrough<Option<Deployment>>,

A through relationship queries and eager-loads like #[has_many] or #[has_one]: project.deployments reads loaded deployments, project.deployments() builds a query, and Project::deployments works with with, has, and with_count. Because the query joins the intermediate table, you may also filter on its columns (for example, fetching only deployments in the production environment):

rust
let deployments = project    .deployments()    .filter(Environment::name.eq("production"))    .get()    .await?;

A through relationship is read-only because it cannot determine which intermediate environment should own a new deployment. Create deployments through their environment instead, such as create!(environment.deployments() { .. }). Attempting to create through project.deployments() fails before inserting anything and returns an error naming Environment::deployments.

Filtered relationships

Sometimes you want a named relationship that exposes only a subset of related rows, such as a user's published posts or admin roles. Pass a filter condition to the relationship attribute alongside the unfiltered relationship:

rust
// src/models/user.rsuse dust::model::{HasMany, model};use crate::models::Post;#[model]pub struct User {    pub id: i64,    // ...    #[has_many]    pub posts: HasMany<Post>,    #[has_many(filter = !Post::published_at.is_null())]    pub published_posts: HasMany<Post>,}

A filtered relationship behaves like any #[has_many]: user.published_posts(), with, with_count, has, has_where, and doesnt_have_where all restrict themselves to matching rows automatically. For example, this query retrieves every user with at least one published post along with those published posts:

rust
use crate::models::User;let authors = User::query()    .has(User::published_posts)    .with(User::published_posts)    .get()    .await?;

The filter expression uses typed columns as in query().filter(...), so column names and value types are verified at compile time. You may combine conditions with & or call a scope such as filter = Post::published(). Every relationship attribute except #[morph_to] supports filter.

Filtering join-row columns

On #[belongs_to_many], filter may also constrain columns on the join row. For example, this relationship returns only roles where the user's role_user membership has level = "admin":

rust
#[belongs_to_many(filter = Membership::level.eq("admin"))]pub admin_roles: BelongsToMany<Role, Membership>,

Creating and updating through filtered relationships

When you create records through a filtered relationship, dust-framework automatically populates any columns constrained with eq so the inserted row satisfies the filter:

rust
use dust::model::create;// Automatically sets `approved` to `true`...let comment = create!(post.approved_comments() { body: "Thanks!" }).await?;// Automatically sets `level` to `"admin"` on the join row...user.admin_roles().attach(&role).await?;

Non-equality filters such as !Post::published_at.is_null() are not populated automatically, so a post created via user.published_posts() remains a draft unless you set published_at yourself.

On a filtered #[belongs_to_many] relationship, write methods (detach, sync, toggle, and update_join_row) affect only join rows matching the filter, leaving other roles untouched:

rust
// Replaces only the user's admin roles, leaving non-admin roles intact...user.admin_roles().sync(&input.role_ids).await?;

Because a user has only one role_user row per role, calling attach on a role the user already holds at another level violates the unique index. To promote an existing membership instead, update the join row through the unfiltered relationship:

rust
use dust::model::joined;user.roles()    .update_join_row(&role, joined!(Membership { level: "admin" }))    .await?;

Combining filters with other relationships

You may combine filter with has-one-of-many and through relationships:

rust
// Selects the latest published post...#[has_one(latest_of_many, filter = !Post::published_at.is_null())]pub latest_published_post: HasOne<Option<Post>>,// Fetches comments only on the user's published posts...#[has_many_through(User::published_posts, Post::comments)]pub published_comments: HasManyThrough<Comment>,

Nested route bindings scoped through a filtered relationship also resolve only matching rows.

Querying related models

Calling a relationship as a method returns a query builder already scoped to that parent model. For example, user.posts() returns a db::Builder<Post> restricted to that user's posts, supporting every query builder clause. This handler returns the signed-in user's drafts, newest first:

rust
use dust::prelude::*;use crate::models::{Post, User};pub async fn drafts(    Authenticated(user): Authenticated<User>,) -> dust::Result<Json<Vec<Post>>> {    let drafts = user        .posts()        .filter(Post::published_at.is_null())        .order_by(Post::created_at.desc())        .get()        .await?;    Ok(Json(drafts))}

Counting and deleting related rows follow the same pattern:

rust
let count = user.posts().count().await?;user.posts().filter(Post::votes.lt(-10)).delete().await?;

Because dust-framework wraps each filter call in its own parentheses, combining conditions with | still restricts results to that user's posts: user.posts().filter(Post::votes.gt(100) | Post::title.eq("Hello")) will never match another user's post.

On a #[belongs_to_many] relationship, the method returns model::ManyToMany, which exposes both join-table writes and shortcuts like get() and count(). To chain additional query clauses such as filter or order_by, call query() first:

rust
let post = Post::find_or_fail(1).await?;let tags = post.tags().query().order_by(Tag::name).get().await?;

Filtering by related rows

You can filter a model query based on whether related records exist using has, has_where, doesnt_have, and doesnt_have_where:

rust
use crate::models::{Post, User};let authors = User::query()    .has(User::posts)    .get()    .await?;let popular = User::query()    .has_where(User::posts, Post::votes.gt(10))    .get()    .await?;let lurkers = User::query()    .doesnt_have(User::posts)    .get()    .await?;let unrecognized = User::query()    .doesnt_have_where(User::posts, Post::votes.gt(10))    .get()    .await?;

User::posts.exists() produces the same check as a composable db::Condition, allowing you to combine it with |, &, and ! or nest it inside has_where. For example, these queries find users who either have a post or a @example.com address, and users who have at least one post with comments:

rust
let users = User::query()    .filter(User::posts.exists() | User::email.ends_with("@example.com"))    .get()    .await?;let commented = User::query()    .has_where(User::posts, Post::comments.exists())    .get()    .await?;

exists_where builds the condition form of has_where so you can combine it with | or other filters. For example, this finds users who either have a post with more than 10 votes or a @example.com address:

rust
let users = User::query()    .filter(        User::posts.exists_where(Post::votes.gt(10))            | User::email.ends_with("@example.com"),    )    .get()    .await?;

Filtering by the number of related rows

When checking for at least one related row isn't enough (such as a leaderboard listing authors with three or more posts), use User::posts.count() and compare it against a number:

rust
use crate::models::{Post, User};let prolific = User::query()    .filter(User::posts.count().ge(3))    .get()    .await?;

To count only related rows matching a condition, use count_where. For example, this finds users who have at least three posts with more than 10 votes:

rust
let popular = User::query()    .filter(User::posts.count_where(Post::votes.gt(10)).ge(3))    .get()    .await?;

Because count comparisons return a standard db::Condition, you can combine them with | or nest them inside has_where. These queries find users who have either exactly one post or a @example.com address, and users who have a post with at least five comments:

rust
let users = User::query()    .filter(User::posts.count().eq(1) | User::email.ends_with("@example.com"))    .get()    .await?;let discussed = User::query()    .has_where(User::posts, Post::comments.count().ge(5))    .get()    .await?;

You may also pass a relationship count to order_by to sort models by how many related records they have. For example, this retrieves the ten users with the most posts:

rust
let busiest = User::query()    .order_by(User::posts.count().desc())    .limit(10)    .get()    .await?;

Relationship counts support eq, ne, lt, le, gt, ge, and between with whole numbers.

Eager loading

Suppose you list 25 posts alongside each author's name. Querying each post's author inside the loop would run 26 queries: one for the posts and one per author. Eager loading reduces this to two queries. Pass a relationship to with to load it across every model returned by the query:

rust
use crate::models::Post;let posts = Post::query().with(Post::user).get().await?;for post in &posts {    println!("{} by {}", post.title, post.user.name);}

dust-framework runs the posts query first, then runs a single query to fetch all referenced users and populates each post's user field. To eager-load multiple relationships at once, pass them as a tuple (one query runs per relationship):

rust
let posts = Post::query()    .with((Post::user, Post::comments))    .get()    .await?;

How to load

Four methods cover almost every loading need:

Situation Call
Loading relationships for the rows a query returns with (or with((A, B)) for several)
Loading onto a model or Vec you already hold load
Loading only what is still missing load_missing
Computing a count or aggregate without loading rows with_count, with_sum, with_max, and the other aggregates

with runs after the main query, so it costs one additional query per relationship rather than one per row. load always re-runs the relationship query and replaces loaded values; load_missing skips models and nested levels that are already loaded, which makes it the safe choice for helpers that may receive pre-loaded data.

A relationship method such as post.comments() is not eager loading: it returns a query scoped to that one parent, and you run it explicitly. Use it when you need a single relationship on demand, or when you need to paginate or aggregate related rows.

Nested eager loading

To eager-load relationships of related models, chain with on the relationship descriptor. For example, this loads every user's posts along with each post's comments and tags:

rust
use crate::models::{Post, User};let users = User::query()    .with(User::posts.with((Post::comments, Post::tags)))    .get()    .await?;

Constraining eager loads

To filter, sort, or limit the related records fetched during eager loading, pass a closure to the relationship's query method. For example, this loads each user's three most recent published posts:

rust
use crate::models::{Post, User};let users = User::query()    .with(User::posts.query(|posts| {        posts            .filter(!Post::published_at.is_null())            .order_by(Post::published_at.desc())            .limit(3)    }))    .get()    .await?;

limit and offset inside an eager load apply per parent record rather than globally, so every user receives up to three posts. Always include an order_by when limiting an eager load so the selection is deterministic.

You may chain with and query in either order and nest constraints at multiple levels. For example, this loads each user's three most recent published posts along with only the approved comments on those posts:

rust
use crate::models::{Comment, Post, User};let users = User::query()    .with(        User::posts            .query(|posts| {                posts                    .filter(!Post::published_at.is_null())                    .order_by(Post::published_at.desc())                    .limit(3)            })            .with(Post::comments.query(|comments| {                comments.filter(Comment::approved.eq(true))            })),    )    .get()    .await?;

Counting related rows

To retrieve the number of related records without loading the records themselves, call with_count on the query and read the result with count() on the relationship field:

rust
use crate::models::Post;let posts = Post::query().with_count(Post::comments).get().await?;for post in &posts {    println!("{} has {} comments", post.title, post.comments.count());}

Pass a constrained relationship to count only a subset of related rows. For example, this counts each post's approved comments:

rust
use crate::models::{Comment, Post};let posts = Post::query()    .with_count(Post::comments.query(|comments| {        comments.filter(Comment::approved.eq(true))    }))    .get()    .await?;

Sums, extremes, averages, and existence

Alongside counts, dust-framework can compute sums, averages, minimums, and maximums over a related model's columns without loading the related rows. For example, an author directory can fetch each user's total post votes and most recent publication timestamp by calling with_sum, with_max, with_min, or with_avg and reading the value from the matching method on the relationship field:

rust
use dust::time::Timestamp;use crate::models::{Post, User};let users = User::query()    .with_sum(User::posts, Post::votes)    .with_max(User::posts, Post::published_at)    .get()    .await?;for user in &users {    let votes: i64 = user.posts.sum(Post::votes);    let latest: Option<Timestamp> = user.posts.max(Post::published_at);}

The return type depends on the aggregate and column type:

Method Columns Return type
sum(column) Numeric columns i64 for integers, f64 for floats, Decimal for decimals (0 when no related rows exist)
avg(column) Numeric columns Option<f64>
max(column), min(column) Numbers, text, dates, and times Option<T> for the column's inner type

Use with_exists to check whether any related row exists and read the boolean via exists(). Like with_count, it accepts a single relationship or a tuple:

rust
let users = User::query()    .with_exists((User::posts, User::profile))    .get()    .await?;let writers = users    .iter()    .filter(|user| user.posts.exists())    .count();

Constrained relationships work with every aggregate method, and you may also aggregate join-row columns such as with_max(User::roles, Membership::expires_at). A single relationship field can store multiple computed aggregates simultaneously (for example, both with_count(User::posts) and with_sum(User::posts, Post::votes)).

Because model queries hydrate every column of the model, they do not expose select or add_select. These relationship aggregate methods cover most summary views; for arbitrary custom projections, query db::table into a struct deriving db::FromRow.

Loading into models you already have

When you already hold a model (such as one injected via route model binding) or a Vec of models, call load with any relationship or tuple accepted by with:

rust
use dust::prelude::*;use crate::models::{Post, User};pub async fn show(mut user: User) -> dust::Result<Json<User>> {    user.load(User::posts.with(Post::comments)).await?;    Ok(Json(user))}
rust
let mut users = User::all().await?;users.load((User::posts, User::profile)).await?;

You may also constrain load with .query(..), as shown in constrained eager loads:

rust
user.load(User::posts.query(|posts| {    posts        .filter(Post::published_at.is_not_null())        .order_by(Post::published_at.desc())        .limit(5)})).await?;

load always executes its query and replaces any previously loaded values. When some models may already have a relationship loaded, use load_missing instead. For example, if a helper renders posts with their authors and some callers have already eager-loaded Post::user, load_missing queries only the missing authors and skips the query altogether when every post already has one:

rust
use dust::prelude::*;use crate::models::Post;pub async fn render_feed(mut posts: Vec<Post>) -> dust::Result<Json<Vec<Post>>> {    posts.load_missing(Post::user).await?;    Ok(Json(posts))}

Nested relationships also skip already-loaded relations at each level. This loads posts for users that haven't loaded them yet, then loads comments for every post missing them, including posts that were already loaded:

rust
users.load_missing(User::posts.with(Post::comments)).await?;

Loading counts and aggregates

load_count counts related rows on models you already hold, mirroring with_count on queries. load_exists, load_sum, load_max, load_min, and load_avg also work on single models and Vec slices. This handler shows a user from route model binding with their post count and total votes:

rust
use dust::prelude::*;use crate::models::{Post, User};pub async fn show(mut user: User) -> dust::Result<Json<User>> {    user.load_count(User::posts).await?;    user.load_sum(User::posts, Post::votes).await?;    Ok(Json(user))}

You may also call these loaders on an already-loaded relationship field, for example counting each post's comments after loading a user's posts:

rust
user.load(User::posts).await?;user.posts.load_count(Post::comments).await?;

Having a count from with_count does not mark the relationship itself as loaded, so load_missing will still load the related models. Constraints passed to load_missing apply only to models that do not yet have the relationship loaded; models that already hold loaded records keep them unchanged unless you call load.

Reading loaded relationships

Once loaded, a relationship field dereferences directly to its underlying value (User for BelongsTo<User>, &[Comment] for HasMany<Comment>):

rust
let post = Post::query().with((Post::user, Post::comments)).find_or_fail(1).await?;let author = &post.user.name;let count = post.comments.len();for comment in &post.comments {    // ...}

Accessing a relationship that has not been loaded panics with a message naming the missing eager load:

text
Post::comments isn't loaded; add `.with(Post::comments)` to the query

When a relationship might or might not have been loaded, check is_loaded() or read it safely with try_loaded(), which returns Option<&T> without panicking:

rust
if post.user.is_loaded() {    println!("Author: {}", post.user.name);}if let Some(comments) = post.comments.try_loaded() {    println!("{} comments loaded", comments.len());}

If you loaded a relationship rather than calling with_count or with_exists, post.comments.count() and post.comments.exists() still work by inspecting the loaded records. Reading any other aggregate (such as sum, max, min, or avg) that was not requested panics with the exact call to add, such as add `.with_max(User::posts, Post::votes)` to the query.

Creating and updating related models

To insert a child record belonging to an existing parent, pass the parent's relationship query to create!. dust-framework populates the foreign key (post_id) automatically:

rust
use dust::model::create;use dust::prelude::*;use crate::models::{Post, User};pub async fn store(    post: Post,    Authenticated(user): Authenticated<User>,) -> dust::Result<Redirect> {    create!(post.comments() { body: "First!", user: &user }).await?;    Ok(Redirect::back())}

Relationship creates also accept a fill struct (create!(post.comments() { ..input })) or a list of records:

rust
let comments = create!([    post.comments() { body: "One", user: &user },    post.comments() { body: "Two", user: &user },]).await?;

On a #[belongs_to_many] relationship, create! inserts both the new related model and its linking row in the join table:

rust
let tag = create!(post.tags() { name: "Rust" }).await?;

When you need to build the insert dynamically, call post.comments().create() for a pre-populated create builder, or create_many to insert a list of builders or fill structs inside one transaction:

rust
let comment = post    .comments()    .create()    .body("Nice post!")    .user(&user)    .await?;let tags = post    .tags()    .create_many([        Tag::create().name("Rust"),        Tag::create().name("dust-framework"),    ])    .await?;

You may also insert a parent and its related models in a single create! call by nesting a struct literal for the relationship field. All inserts run in one transaction and hydrate the relationship in memory:

rust
let post = create!(Post {    title: "Hello",    user: User {        name: "Abigail",        email: "abigail@example.com",        password: "secret",    },}).await?;

To learn more about nested and batched creates, check out Creating related models together.

To reassign a #[belongs_to] relationship to a different parent (such as transferring a post to another author), assign the new parent model inside update!:

rust
use dust::model::update;update!(post { user: &user }).await?;

dust-framework updates user_id in the database and refreshes post.user in memory so you can read it immediately without another query.

Attaching and syncing join rows

Unlike one-to-many relationships where a foreign key lives directly on the child table, many-to-many relationships store their links in an intermediate join table (such as post_tag connecting posts and tags). Rather than inserting and deleting rows in that join table manually, dust-framework provides helper methods directly on your #[belongs_to_many] relationship for attaching, detaching, syncing, toggling, and updating join rows.

To link one or more related records to a model, pass a model, a primary key, or an array, Vec, or slice of either to attach:

rust
post.tags().attach(&rust).await?;post.tags().attach([&rust, &release]).await?;post.tags().attach([1, 2]).await?;

To remove links from the join table without deleting the related models themselves, call detach. It accepts the same arguments as attach and returns the number of removed join rows:

rust
post.tags().detach(&release).await?;post.tags().detach([1, 2]).await?;

When a form submits the complete set of related records a model should have, such as the tags selected when editing a post, use sync. It attaches any IDs that are not yet linked and detaches any existing links omitted from the list:

rust
use dust::prelude::*;use crate::models::Post;#[dust::input]#[validate(anyone)]pub struct PostTags {    pub tag_ids: Vec<i64>,}pub async fn update(post: Post, Valid(input): Valid<PostTags>) -> dust::Result<Redirect> {    post.tags().sync(&input.tag_ids).await?;    Ok(Redirect::back())}

If you want to flip the link state for a set of records, detaching any that are currently linked and attaching any that are not, call toggle:

rust
post.tags().toggle([&rust, &release]).await?;

Both sync and toggle return a model::SyncChanges struct listing the attached, detached, and updated keys:

rust
let changes = post.tags().sync([2, 3]).await?;if !changes.attached.is_empty() {    // Notify followers of the new tags...}

To set extra columns on join rows as you link them, pair each model or key with db::values!. attach and toggle write those columns on newly inserted rows, while sync updates them on every retained row as well:

rust
use dust::db;post.tags()    .attach((&rust, db::values! { pinned: true }))    .await?;post.tags()    .sync([        (&release, db::values! { pinned: true }),        (&rust, db::values! { pinned: false }),    ])    .await?;

To update extra columns on an existing join row without attaching or detaching any records, call update_join_row:

rust
post.tags()    .update_join_row(&rust, db::values! { pinned: true })    .await?;

To read these columns back with the related models and have the compiler check their names and types, describe them in a join row.

Defining join-row models

A join table often holds more than the two foreign keys. For example, a user's role may expire via an expires_at column on role_user. To read extra join columns alongside related models, define a struct annotated with #[join_row] containing a field for each column:

rust
// src/models/membership.rsuse dust::model::join_row;use dust::time::Timestamp;#[join_row(table = "role_user")]pub struct Membership {    pub level: String,    pub expires_at: Option<Timestamp>,    pub created_at: Timestamp,    pub updated_at: Timestamp,}

List only the join-table columns you care about. By convention, the table name is the snake-case struct name (such as role_user for RoleUser); use #[join_row(table = "..")] to specify a different table name. Field types, #[column("..")], #[default], and created_at / updated_at timestamps work like model fields, and #[join_row] automatically derives Clone, Debug, and Serialize so join attributes serialize under a join key.

When defining the relationship on the model, pass the join-row struct as the second type parameter on both sides of the relationship (the relationship automatically inherits the table name from the join row):

rust
// src/models/user.rsuse dust::model::{BelongsToMany, model};use crate::models::{Membership, Role};#[model]pub struct User {    pub id: i64,    // ...    #[belongs_to_many]    pub roles: BelongsToMany<Role, Membership>,}
rust
// src/models/role.rs#[model]pub struct Role {    pub id: i64,    pub name: String,    #[belongs_to_many]    pub users: BelongsToMany<User, Membership>,}

Accessing join-row attributes

Eager loading populates each item of user.roles as a model::Joined<Role, Membership>, which dereferences to Role and exposes the join-table attributes on .join:

rust
use dust::prelude::*;use crate::models::User;pub async fn show(mut user: User) -> dust::Result<Json<User>> {    user.load(User::roles).await?;    let admin_until = user        .roles        .iter()        .find(|role| role.name == "admin")        .and_then(|role| role.join.expires_at);    tracing::info!(?admin_until, "Admin membership");    Ok(Json(user))}

Because Joined<Role, Membership> dereferences to Role, role fields and methods work directly on it, &Joined<Role, Membership> passes anywhere &Role is expected, and relationship writes accept it directly:

rust
let role = &user.roles[0];println!("{} ({})", role.name, role.join.level);audit_role(role); // accepts `&Role`user.roles().detach(role).await?;

Querying join rows directly

To query a user's roles together with their join rows without hydrating them onto user (for example, when paginating a long list), call joined() on the relationship, chain optional clauses with query, and finish with get, first, paginate, simple_paginate, or cursor. For example, this query paginates the user's roles 15 at a time, ordered by when each membership was created, and returns each Role paired with its Membership join row:

rust
let roles = user    .roles()    .joined()    .query(|roles| roles.order_by(Membership::created_at.desc()))    .paginate(15)    .await?;

find and find_or_fail fetch a single attached model along with its join row by primary key, with find returning None if the records are not linked:

rust
let expires_at = user    .roles()    .joined()    .find(2)    .await?    .and_then(|role| role.join.expires_at);

Calling user.roles().get() directly continues to return plain Role models without join rows.

Filtering and ordering by join-row columns

#[join_row] generates typed column constants (such as Membership::expires_at) that work in any query joining the join table: relationship queries, constrained eager loads, has_where, doesnt_have_where, and with_count. You may define reusable query scopes and instance methods directly on the join-row struct:

rust
use dust::db::Condition;impl Membership {    /// Memberships that haven't expired...    pub fn current() -> Condition {        Membership::expires_at.is_null() | Membership::expires_at.gt(dust::now())    }    /// Whether this membership hasn't expired...    pub fn is_current(&self) -> bool {        self.expires_at            .is_none_or(|expires_at| expires_at > dust::now().timestamp())    }}// Load the user's active roles, newest first...let user = User::query()    .with(User::roles.query(|roles| {        roles            .filter(Membership::current())            .order_by(Membership::created_at.desc())    }))    .find_or_fail(1)    .await?;// Find users with an active admin role...let admins = User::query()    .has_where(User::roles, Role::name.eq("admin") & Membership::current())    .get()    .await?;// Find users with no active roles...let lapsed = User::query()    .doesnt_have_where(User::roles, Membership::current())    .get()    .await?;

Once user.roles is loaded, is_current lets you filter expired roles in memory:

rust
let expired: Vec<&str> = user    .roles    .iter()    .filter(|role| !role.join.is_current())    .map(|role| role.name.as_str())    .collect();

To check whether a user holds an active role without loading all of their roles (for instance inside an authorization policy), filter the relationship query and call exists:

rust
let is_admin = user    .roles()    .query()    .filter(Role::name.eq("admin") & Membership::current())    .exists()    .await?;

latest, oldest, pluck, and value accept join-row columns as well:

rust
let newest: Vec<String> = user    .roles()    .query()    .latest(Membership::created_at)    .pluck(Role::name)    .await?;

Writing join-row columns

To populate join-table columns in attach, sync, toggle, or update_join_row with compile-time type checking, pair each related model with joined!. Standard Rust field shorthand works here as well:

rust
use dust::model::joined;use dust::prelude::*;#[dust::input]#[validate(anyone)]pub struct GrantRole {    pub level: String,}pub async fn grant(    user: User,    role: Role,    Valid(GrantRole { level }): Valid<GrantRole>,) -> dust::Result<Redirect> {    user.roles()        .attach((            &role,            joined!(Membership {                level,                expires_at: dust::now().plus(30.days()),            }),        ))        .await?;    Ok(Redirect::back())}

Syncing and updating join rows

Pass an array of pairs to sync, or pass the related model and joined! values to update_join_row:

rust
user.roles()    .sync([        (1, joined!(Membership { level: "owner", expires_at: None })),        (            2,            joined!(Membership {                level: "member",                expires_at: dust::now().plus(7.days()),            }),        ),    ])    .await?;user.roles()    .update_join_row(&role, joined!(Membership { expires_at: None }))    .await?;

When syncing a dynamic list of roles with join-row values, collect the pairs into a Vec before passing them to sync:

rust
let memberships: Vec<_> = input    .roles    .into_iter()    .map(|role| {        (            role.id,            joined!(Membership {                level: role.level,                expires_at: role.expires_at,            }),        )    })    .collect();user.roles().sync(memberships).await?;

Partial updates with fill structs

For partial updates such as PATCH forms, define a fill struct targeting the join row with Sometimes fields and spread ..input at the end of joined! so omitted fields keep their existing values:

rust
use dust::prelude::*;use dust::validation::Sometimes;#[dust::input(fills = Membership)]#[validate(anyone)]pub struct EditMembership {    pub level: Sometimes<String>,    pub expires_at: Sometimes<Option<Timestamp>>,}pub async fn update(    user: User,    role: Role,    Valid(input): Valid<EditMembership>,) -> dust::Result<Redirect> {    user.roles().update_join_row(&role, joined!(Membership { ..input })).await?;    Ok(Redirect::back())}

Building join-row values dynamically

When the join columns to write depend on runtime logic, call Membership::values() for a fluent builder with column setters and .fill(input), which can be passed anywhere joined! is accepted:

rust
let mut values = Membership::values().fill(input);if role.name == "admin" {    values = values.expires_at(dust::now().plus(30.days()));}user.roles().update_join_row(&role, values).await?;

Creating and attaching in a transaction

To create a new role and attach it with join-row columns atomically, wrap both writes in a transaction:

rust
use dust::db;use dust::model::create;let role = db::transaction(async |_| {    let role = create!(Role { name: "Billing" }).await?;    user.roles().attach((&role, joined!(Membership { level: "owner" }))).await?;    Ok(role)}).await?;

Polymorphic relationships

Sometimes one model can attach to multiple parent types, such as users commenting on both blog posts and videos. Rather than creating separate comments tables, a polymorphic relationship stores every comment in one table, recording each parent's type and key.

The comments table holds a type column and a key column for the parent. The schema builder's morphs helper adds both columns and indexes the pair:

rust
tx.schema()    .create("comments", |table| {        table.id();        table.text("body");        table.morphs("commentable");        table.timestamps();    })    .await?;

morphs("commentable") adds a string commentable_type column and a big integer commentable_id column. Use uuid_morphs or ulid_morphs when parents use UUID or ULID keys, and the nullable_ variants when the parent is optional.

Declaring polymorphic relationships

First, list every parent model a comment can attach to in an enum marked #[morph], where each variant holds one model:

rust
// src/models/comment.rsuse dust::model::{MorphTo, MorphType, model, morph};use dust::time::Timestamp;use crate::models::{Post, Video};#[morph]pub enum Commentable {    Post(Post),    Video(Video),}#[model]pub struct Comment {    pub id: i64,    pub body: String,    pub commentable_type: MorphType<Commentable>,    pub commentable_id: i64,    pub created_at: Timestamp,    pub updated_at: Timestamp,    #[morph_to]    pub commentable: MorphTo<Commentable>,}

A #[morph_to] field reads the two columns named after it (commentable_type and commentable_id). If the parent is optional, wrap both columns and the relationship (MorphTo<Option<Commentable>>) in Option.

The type column stores each model's morph name, defaulting to the struct's snake-case name (post for Post, blog_post for BlogPost). To customize the stored name (for example, to preserve existing values in the database), annotate the model with #[model(morph = "..")]:

rust
#[model(morph = "clip")]pub struct Video {    // ...}

The #[morph] enum defines the complete set of allowed parents: MorphType<Commentable> only decodes and writes names listed in the enum (post and clip), and all models in the enum must share the same primary key type and distinct morph names. If you later rename a model struct, keep its original database identifier with #[model(morph = "..")].

Next, declare the inverse relationship on each parent model by pointing #[morph_many] or #[morph_one] at the child's #[morph_to] descriptor (typos or unlisted parents fail at compile time):

rust
// src/models/post.rsuse dust::model::{MorphMany, MorphOne, model};use crate::models::{Comment, Image};#[model]pub struct Post {    pub id: i64,    pub title: String,    #[morph_many(Comment::commentable)]    pub comments: MorphMany<Comment>,    #[morph_one(Image::imageable)]    pub image: MorphOne<Option<Image>>,}

#[morph_many] and #[morph_one] mirror #[has_many] and #[has_one], filtering by the parent's morph type automatically so a video's comments never appear under a post sharing the same ID:

rust
let post = Post::query()    .with((Post::comments, Post::image))    .find_or_fail(id)    .await?;let recent = post    .comments()    .order_by(Comment::created_at.desc())    .limit(10)    .get()    .await?;

If the parent key uses a non-default column name, pass local_key:

rust
#[morph_many(Comment::commentable, local_key = "uuid")]pub comments: MorphMany<Comment>,

On #[morph_one], you may also use latest_of_many and the other of_many options to pick a single standout record:

rust
#[morph_one(Image::imageable, latest_of_many)]pub latest_image: MorphOne<Option<Image>>,

Loading polymorphic relationships

Load a #[morph_to] relationship with with as you would a #[belongs_to]. The loaded field dereferences to the morph enum, so you can match on it to handle each parent type:

rust
use dust::prelude::*;use crate::models::{Comment, Commentable};pub async fn index() -> dust::Result<Json<Vec<Comment>>> {    let comments = Comment::query()        .with(Comment::commentable)        .order_by(Comment::created_at.desc())        .limit(50)        .get()        .await?;    for comment in &comments {        let _title = match &*comment.commentable {            Commentable::Post(post) => post.title.as_str(),            Commentable::Video(video) => video.name.as_str(),        };    }    Ok(Json(comments))}

Loading a non-optional MorphTo<Commentable> fails if a comment points to a deleted parent; use MorphTo<Option<Commentable>> if orphaned records are possible.

To eager-load nested relationships specific to each parent variant, chain morph_with for each target model (relationships belonging to models outside the morph enum fail to compile). The example below loads every comment along with its parent, eager-loading the user relationship for posts and the channel and tags relationships for videos:

rust
let comments = Comment::query()    .with(        Comment::commentable            .morph_with(Post::user)            .morph_with((Video::channel, Video::tags)),    )    .get()    .await?;

You may also customize the query for a specific parent type using query::<T>:

rust
let comments = Comment::query()    .with(        Comment::commentable.query::<Post>(|posts| {            posts.with(Post::user).with_count(Post::comments)        }),    )    .get()    .await?;

load and load_missing accept the same descriptors when eager-loading onto models you have already retrieved, and comment.commentable().first() fetches a single comment's parent on demand:

rust
// Eager-load missing parents (and each post's author) onto an existing collection...comments    .load_missing(Comment::commentable.morph_with(Post::user))    .await?;// Fetch a single comment's parent on demand...match comment.commentable().first().await? {    Some(Commentable::Post(post)) => {        // ...    }    Some(Commentable::Video(video)) => {        // ...    }    None => {        // The parent was deleted or the morph columns are null...    }}

Because #[morph_to] points to one record, passing it to with_count fails to compile; use has instead.

Filtering by the model a relationship refers to

has(Comment::commentable) matches comments whose parent exists, while doesnt_have matches comments whose parent is missing. To filter on a specific parent type's columns, narrow the relationship with of::<Post>(). Both has_where and doesnt_have_where restrict the query to comments belonging to that parent type (comments on videos are excluded):

rust
// Comments on posts whose title mentions Rust...let about_rust = Comment::query()    .has_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))    .get()    .await?;// Comments on posts whose title does not mention Rust...let other_posts = Comment::query()    .doesnt_have_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))    .get()    .await?;

To match across multiple parent types in one query, combine exists_where conditions with |. The example below retrieves every comment that belongs either to a post whose title contains "Rust" or to a video whose name contains "Rust":

rust
let about_rust = Comment::query()    .filter(        Comment::commentable.of::<Post>().exists_where(Post::title.contains("Rust"))            | Comment::commentable.of::<Video>().exists_where(Video::name.contains("Rust")),    )    .get()    .await?;

To filter comments belonging to a specific model instance, use is(&post). It matches both commentable_type and commentable_id, preventing collisions with a video sharing the same ID:

rust
let comments = Comment::query().filter(Comment::commentable.is(&post)).get().await?;

Calling post.comments() queries the same rows from the parent side.

To filter solely by parent type without a model instance, compare the type column against MorphType::of:

rust
// Comments belonging to videos...let video_comments = Comment::query()    .filter(Comment::commentable_type.eq(MorphType::of::<Video>()))    .get()    .await?;// Comments belonging to any parent type except posts...let non_post_comments = Comment::query()    .filter(Comment::commentable_type.ne(MorphType::of::<Post>()))    .get()    .await?;

Writing polymorphic relationships

Creating a comment through its parent's relationship populates both the type and ID columns automatically:

rust
use dust::model::create;let comment = create!(post.comments() { body: "Great post!" }).await?;

You may also assign any model in the morph enum directly to the #[morph_to] field in create! or update!:

rust
use dust::model::{create, update};let mut comment = create!(Comment { body: "Great video!", commentable: &video }).await?;update!(comment { commentable: &post }).await?;

dust-framework hydrates comment.commentable with the assigned model immediately, so reading it requires no extra query.

Nested creation works like #[has_many]: creating a post with inline comments populates post.comments as well as each comment's commentable field:

rust
let post = create!(Post {    title: "Hello",    user: &user,    comments: [Comment { body: "First!" }, Comment { body: "Second!" }],}).await?;

The Post inside each comment's commentable field does not carry its own loaded relationships, so post.comments is unloaded there. Factory has calls hydrate commentable as well, whereas post.comments().create() returns only the comment's columns until you load Comment::commentable.

You may also pass a create! builder or a factory to a #[morph_to] field, inserting the parent first inside the same transaction:

rust
// Insert a new video and comment together in one transaction...let comment = create!(Comment {    body: "First!",    commentable: create!(Video { name: "Premiere" }),}).await?;// Or default a comment factory's parent to a new post...#[factory(Comment)]pub struct CommentFactory;impl CommentFactory {    fn definition(fake: &mut Faker) -> impl IntoCreate<Comment> {        create!(Comment {            body: fake.sentence(),            commentable: Post::factory(),        })    }}

Many-to-many polymorphic relationships

Tags are a classic example of a polymorphic many-to-many relationship: posts and videos can share tags, and each tag can be applied to many posts and videos. One taggables join table stores every link, using morphs("taggable") to create the two polymorphic columns (taggable_type and taggable_id) alongside tag_id:

rust
tx.schema()    .create("taggables", |table| {        table.foreign_id("tag_id");        table.morphs("taggable");        table.timestamps();    })    .await?;

Because a join table has no standalone model for #[morph_to], its join row holds a MorphKey<Taggable> field that bundles the taggable_type and taggable_id columns into a single (type, id) pair:

rust
// src/models/tag.rsuse dust::model::{MorphKey, MorphedByMany, join_row, model, morph};use dust::time::Timestamp;use crate::models::{Post, Video};#[morph]pub enum Taggable {    Post(Post),    Video(Video),}#[join_row(table = "taggables")]pub struct Tagging {    pub taggable: MorphKey<Taggable>,    pub created_at: Timestamp,    pub updated_at: Timestamp,}#[model]pub struct Tag {    pub id: i64,    pub name: String,    #[morphed_by_many(Tagging::taggable)]    pub posts: MorphedByMany<Post>,    #[morphed_by_many(Tagging::taggable)]    pub videos: MorphedByMany<Video>,}

On each taggable model, declare #[morph_to_many] pointing at the same MorphKey field:

rust
// src/models/post.rsuse dust::model::{MorphToMany, model};use crate::models::{Tag, Tagging};#[model]pub struct Post {    pub id: i64,    pub title: String,    #[morph_to_many(Tagging::taggable)]    pub tags: MorphToMany<Tag, Tagging>,}

The relationship inherits the join table name from Tagging and expects the related key column to be tag_id (override it with related_join_key on #[morph_to_many] or foreign_join_key on #[morphed_by_many]). On Tag, declare one #[morphed_by_many] field per taggable model type.

Polymorphic many-to-many relationships support the same query and write methods as #[belongs_to_many], automatically scoping every query and write by taggable_type so syncing a video's tags never touches a post's tags:

rust
use dust::model::create;post.tags().sync([rust.id, dust.id]).await?;video.tags().attach(&rust).await?;let tag = create!(post.tags() { name: "Tutorial" }).await?;

Because Post::tags includes Tagging in its field type (MorphToMany<Tag, Tagging>), each loaded tag exposes its join-table row on .join, where you can read timestamps, any extra join columns, or the morph pair through morph() and key():

rust
let post = Post::query().with(Post::tags).find_or_fail(1).await?;for tag in &post.tags {    let name = &tag.name;    let tagged_at = tag.join.created_at;    let morph = tag.join.taggable.morph(); // MorphType<Taggable> ("post")    let id = tag.join.taggable.key();      // &i64 (1)}

If you do not need to read join-table columns when iterating over tags, you may leave Tagging out of the field type and write MorphToMany<Tag> (or MorphedByMany<Post> on Tag):

rust
#[model]pub struct Video {    pub id: i64,    pub name: String,    #[morph_to_many(Tagging::taggable)]    pub tags: MorphToMany<Tag>,}

With MorphToMany<Tag>, iterating &video.tags yields plain Tag models without .join. Because the #[morph_to_many(Tagging::taggable)] attribute still points to Tagging, dust-framework continues to populate join-table timestamps automatically and still accepts joined! values when writing extra columns.

Deleting related rows

Deleting a parent does not delete its children by itself. You choose one of three mechanisms, and they differ in whether your model code sees the deletion:

  • A cascading foreign key removes children in the same statement. It is the fastest and removes every child at the database level, but it runs inside the database: child hooks, Deleted events, and search syncs do not run. See Cascades and deletes.
  • destroy loads each child model and deletes it one by one, so hooks and events run. Use it when side effects matter.
  • A relationship query deletes matching rows in one statement and skips hooks and events, like any bulk delete.
rust
// Declared in the migration: children follow the parent in the database.table.foreign_id("post_id").constrained().cascade_on_delete();// Deletes the post and, through the foreign key, its comments without running Comment hooks.post.delete().await?;// Loads and deletes each comment, running its hooks and dispatching Deleted events.Comment::destroy([1, 2, 3]).await?;// One statement: fast, but no per-comment hooks or events.post.comments().delete().await?;

For a #[belongs_to_many] relationship, delete on the relationship deletes the related models themselves, while detach removes only the join rows:

rust
post.tags().detach(&tag).await?; // The tag row stays.post.tags().delete().await?;     // The tag rows are deleted too.

If you rely on database cascades, enable foreign keys on SQLite and keep search indexes in mind: a cascaded delete leaves indexed children behind until you re-import or sync them.

Common pitfalls

  • A missing Option is a runtime error, not a compile error. HasOne<Profile> and BelongsTo<User> fail to load when no row exists; declare HasOne<Option<Profile>> or BelongsTo<Option<User>> when absence is valid.
  • Conventions drive the keys. #[has_many] expects {model}_id on the child, and #[belongs_to] expects {field}_id on this table. When the schema differs, pass foreign_key, owner_key, or local_key rather than renaming the column.
  • A join table needs a unique index. Without table.unique(["post_id", "tag_id"]), attaching the same pair twice can create duplicate links. With it, the database rejects the duplicate.
  • limit in an eager load is per parent. It only selects the right rows when the constraint also has an order_by; otherwise the database picks an arbitrary subset.
  • with_count is not a loaded relationship. The count is available, but post.comments is still unloaded, so load_missing(Post::comments) still runs its query.
  • Scoped bindings need a relationship. Nested route binding resolves the child through a declared relationship; without one, the child binds independently even with scope_bindings.
  • Through relationships are read-only. Create the target through the intermediate model, such as environment.deployments(), not through project.deployments().
  • A filtered relationship only auto-fills equality filters. filter = Post::published.eq(true) populates published on create; filter = !Post::published_at.is_null() does not.
  • with_count does not accept a #[morph_to]. Count through has instead, as the polymorphic section explains.
  • Unloaded access panics. Reading post.comments before loading it is a programming error; use is_loaded() or try_loaded() when the state is uncertain.

Serializing relationships

rust
use dust::prelude::*;use crate::models::User;pub async fn show(mut user: User) -> dust::Result<Json<User>> {    user.load(User::posts).await?;    Ok(Json(user))}

That handler returns a JSON response containing the user along with its loaded posts array:

json
{    "id": 1,    "name": "Taylor",    "posts": [        {            "id": 1,            "user_id": 1,            "title": "Hello"        }    ]}

Related models follow the same serialization rules as top-level models, so any fields marked #[serde(skip)] or #[serde(skip_serializing)] on a related model are also omitted from the response. If a model specifies #[serde(rename_all = "camelCase")], relationship and aggregate keys follow the same casing rule (for example, blogPosts, blogPostsCount, and blogPostsSumVotes).

Serializing aggregates

Loaded relationship aggregates appear alongside the model's columns with suffixes such as _count, _exists, _sum_<column>, and _max_<column> (for example, posts_count, posts_sum_votes, and posts_max_published_at):

rust
let user = User::query()    .with_count(User::posts)    .find_or_fail(1)    .await?;
json
{    "id": 1,    "name": "Taylor",    "posts_count": 1}

Omitting loaded relationships

To serialize a model without any loaded relationships or aggregates, call without_relations(), which returns a copy containing only the model's columns:

rust
Ok(Json(user.without_relations()))
json
{    "id": 1,    "name": "Taylor"}

Serializing join rows

When a relationship includes a join row, each related model serializes with its join attributes nested under join:

json
{    "id": 1,    "name": "Taylor",    "roles": [        {            "id": 2,            "name": "admin",            "join": {                "level": "owner",                "expires_at": null,                "created_at": "2026-11-10T09:00:00Z",                "updated_at": "2026-11-10T09:00:00Z"            }        }    ]}

Serializing polymorphic relationships

A loaded #[morph_to] relationship serializes directly as its underlying model without an enum wrapper tag; the type column (commentable_type) indicates which model the nested object represents:

rust
use dust::prelude::*;use crate::models::Comment;pub async fn show(mut comment: Comment) -> dust::Result<Json<Comment>> {    comment.load(Comment::commentable).await?;    Ok(Json(comment))}

For a comment belonging to a Video, that handler returns:

json
{    "id": 4,    "body": "Great video!",    "commentable_type": "video",    "commentable_id": 1,    "commentable": {        "id": 1,        "name": "Intro"    }}

For a polymorphic many-to-many relationship that includes a join row (such as MorphToMany<Tag, Tagging>), the join row's MorphKey field serializes as an object containing type and id:

rust
pub async fn show(mut post: Post) -> dust::Result<Json<Post>> {    post.load(Post::tags).await?;    Ok(Json(post))}
json
{    "id": 1,    "title": "Hello",    "tags": [        {            "id": 1,            "name": "Rust",            "join": {                "taggable": {                    "type": "post",                    "id": 1                },                "created_at": "2026-11-10T09:00:00Z",                "updated_at": "2026-11-10T09:00:00Z"            }        }    ]}