-
|
I have a query where I need to load entities together with an optional related row. The related row should only be loaded if it matches some condition, for example At first I tried to solve it with I also need pagination and total count for the same query. What is the recommended SeaORM approach here? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I found the answer while testing this a bit more. For this kind of case, The important part is to put the condition for the joined table into the If the condition is added to Example idea: use sea_orm::{
sea_query::Expr,
ColumnTrait, EntityTrait, JoinType, QueryFilter, QuerySelect,
};
let query = food::Entity::find()
.filter(food::Column::Source.ne(Source::User))
.join(
JoinType::LeftJoin,
food::Relation::FoodOverride
.def()
.on_condition(move |_left, right| {
Expr::col((right, food_override::Column::OwnedBy))
.eq(user_id)
.into_condition()
}),
);So the logic becomes: For pagination and total count, I ended up using SeaORM pagination: let paginator = query.paginate(db, 50);
let total = paginator.num_items().await?;
let page = paginator.fetch_page(0).await?;So the final approach is:
That solved it for me. |
Beta Was this translation helpful? Give feedback.
I found the answer while testing this a bit more.
For this kind of case,
find_also_relatedis probably not the best fit. It is nice for simple relation loading, but when the joined row needs its own custom condition, a manualLEFT JOINgives much better control.The important part is to put the condition for the joined table into the
ONclause, not intoWHERE.If the condition is added to
WHERE, theLEFT JOINcan behave like anINNER JOIN, because rows without a matching related record will be filtered out.Example idea: