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§
- Eager
Query - A
QueryBuilderwith relations to load: fromQueryBuilder::with. Itsfetch_*answerLoadedmodels. - Loaded
- A model with the relations
QueryBuilder::withloaded for it. Derefs to the model. - Relation
- How a model
Oreaches related rows ofR: forQueryBuilder::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§
- Relation
Kind - What a
Relationis.
Constants§
- IN_
BATCH - How many keys one
IN (…)list carries; more are sent in more queries.