Skip to content

Commit

Permalink
Join with table alias (SeaQL/sea-orm#852)
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Jul 13, 2022
1 parent d9b1b8f commit fc7b230
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions SeaORM/docs/09-advanced-query/04-custom-joins.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ use sea_query::Expr;
assert_eq!(
cake::Entity::find()
.column_as(filling::Column::Id.count(), "count")
.column_as(
Expr::tbl(Alias::new("fruit_alias"), fruit::Column::Name).into_simple_expr(),
"fruit_name"
)
// construct `RelationDef` on the fly
.join_rev(
// construct `RelationDef` on the fly
JoinType::InnerJoin,
cake_filling::Entity::belongs_to(cake::Entity)
.from(cake_filling::Column::CakeId)
Expand All @@ -19,14 +23,27 @@ assert_eq!(
)
// reuse a `Relation` from existing Entity
.join(JoinType::InnerJoin, cake_filling::Relation::Filling.def())
// join with table alias and custom on condition
.join_as(
JoinType::LeftJoin,
cake::Relation::Fruit
.def()
.on_condition(|_left, right| {
Expr::tbl(right, fruit::Column::Name)
.like("%tropical%")
.into_condition()
}),
Alias::new("fruit_alias")
)
.group_by(cake::Column::Id)
.having(filling::Column::Id.count().equals(Expr::value(2)))
.build(DbBackend::MySql)
.to_string(),
[
"SELECT `cake`.`id`, `cake`.`name`, COUNT(`filling`.`id`) AS `count` FROM `cake`",
"SELECT `cake`.`id`, `cake`.`name`, COUNT(`filling`.`id`) AS `count`, `fruit_alias`.`name` AS `fruit_name` FROM `cake`",
"INNER JOIN `cake_filling` ON `cake_filling`.`cake_id` = `cake`.`id`",
"INNER JOIN `filling` ON `cake_filling`.`filling_id` = `filling`.`id`",
"LEFT JOIN `fruit` AS `fruit_alias` ON `cake`.`id` = `fruit_alias`.`cake_id` AND `fruit_alias`.`name` LIKE '%tropical%'",
"GROUP BY `cake`.`id`",
"HAVING COUNT(`filling`.`id`) = 2",
]
Expand Down

0 comments on commit fc7b230

Please sign in to comment.