Skip to main content

Module eager

Module eager 

Source
Available on crate features model-mysql or model-postgres or model-sqlite only.
Expand description

Eager loading (18.30.0): a Relation names how one model reaches another; QueryBuilder::with loads it for a whole result set in one more query per relation (WHERE fk IN (…)), not one per row.

ⓘ
use rust_web_server::model::{Order, Relation};

impl Post {
    pub fn comments() -> Relation<Post, Comment> { Relation::has_many("post_id") }
    pub fn author() -> Relation<Post, User> { Relation::belongs_to("user_id") }
    pub fn tags() -> Relation<Post, Tag> { Relation::belongs_to_many("post_tags", "post_id", "tag_id") }
}

// Three queries: the posts, their comments, their authors.
let posts = Post::query(&pool)
    .order_by("id", Order::Desc)
    .with(Post::comments())
    .with(Post::author())
    .fetch_all()
    .await?;
for post in &posts {
    let comments: &[Comment] = post.related(&Post::comments());
    let author: Option<&User> = post.one(&Post::author());
    println!("{} by {:?}: {} comments", post.title, author.map(|a| &a.name), comments.len());
}

Related rows that are soft-deleted (#[soft_delete]) are left out, as everywhere else. Keys are sent in batches of IN_BATCH, so a result set larger than that costs one query per batch.

Structs§

EagerQuery
A QueryBuilder with relations to load: from QueryBuilder::with. Its fetch_* answer Loaded models.
Loaded
A model with the relations QueryBuilder::with loaded for it. Derefs to the model.
Relation
How a model O reaches related rows of R: for QueryBuilder::with, and to load the rows of one owner (load) or of many (load_for). Usually returned by an associated function of the owner, so call sites name it:

Enums§

RelationKind
What a Relation is.

Constants§

IN_BATCH
How many keys one IN (…) list carries; more are sent in more queries.