diff --git a/model/src/crud/select.rs b/model/src/crud/select.rs index 011c61c..6f37437 100644 --- a/model/src/crud/select.rs +++ b/model/src/crud/select.rs @@ -555,8 +555,10 @@ fn generate_join_clause(vars: &Vec) -> Result { let mut seen = HashSet::new(); let mut join_clauses = vec![]; + let table_name = T::table_name(); + for var in vars.iter() { - let joins = joins_from_var(&T::table_name(), var, &T::definition())?; + let joins = joins_from_var(&table_name, &table_name, var, &T::definition())?; for (relation, join_clause) in joins.iter() { if seen.insert(relation.clone()) { @@ -569,6 +571,7 @@ fn generate_join_clause(vars: &Vec) -> Result { } fn joins_from_var( + root: &str, parent: &str, var: &Var, model_def: &ModelDef, @@ -583,13 +586,14 @@ fn joins_from_var( .ok_or_else(|| Error::bad_request("undefined field"))?; let id_field_name = (model_def.id_field_name)(); - let join_clause = relation_def.to_join_clause(&parent, &id_field_name); + let join_clause = relation_def.to_join_clause(&parent, &id_field_name, root == parent); let next_parent = format!("{}_{}", parent, name); let mut res = vec![(next_parent.clone(), join_clause)]; res.extend(joins_from_var( + &root, &next_parent, var.as_ref(), &relation_def.model_definition, diff --git a/model/src/relation.rs b/model/src/relation.rs index ce69ca1..b455cc1 100644 --- a/model/src/relation.rs +++ b/model/src/relation.rs @@ -73,33 +73,27 @@ impl RelationDef { } } - pub fn to_join_clause(&self, parent: &str, parent_id_column: &str) -> String { + pub fn to_join_clause(&self, parent: &str, parent_id_column: &str, is_root: bool) -> String { let related_table = (self.model_definition.table_name)(); let related_id_column = (self.model_definition.id_field_name)(); + let alias = if is_root { + self.name.clone() + } else { + format!("{}_{}", parent, self.name) + }; + match &self.reference { Reference::From(column) => { format!( - "LEFT JOIN {} AS {}_{} ON {}.{} = {}.{}", - related_table, - parent, - related_table, - parent, - column, - related_table, - related_id_column + "LEFT JOIN {} AS {} ON {}.{} = {}.{}", + related_table, alias, parent, column, related_table, related_id_column ) } Reference::To(column) => { format!( - "LEFT JOIN {} AS {}_{} ON {}.{} = {}.{}", - related_table, - parent, - related_table, - parent, - parent_id_column, - related_table, - column, + "LEFT JOIN {} AS {} ON {}.{} = {}.{}", + related_table, alias, parent, parent_id_column, related_table, column, ) } Reference::Via((junction_table, from_reference, to_reference)) => { @@ -115,10 +109,9 @@ impl RelationDef { ); let join_relation = format!( - "INNER JOIN {} AS {}_{} ON {}_{}.{} = {}.{}", - related_table, - parent, + "INNER JOIN {} AS {} ON {}_{}.{} = {}.{}", related_table, + alias, parent, junction_table, to_reference,