1
1
use crate :: {
2
2
find_linked, ActiveModelBehavior , ActiveModelTrait , ConnectionTrait , DbErr , DeleteResult ,
3
- EntityTrait , IntoActiveModel , Linked , QueryFilter , QueryResult , QueryTrait , Related , Select ,
4
- SelectModel , SelectorRaw , Statement ,
3
+ EntityTrait , IntoActiveModel , Linked , QueryFilter , QueryResult , QuerySelect , QueryTrait ,
4
+ Related , Select , SelectModel , SelectorRaw , Statement ,
5
5
} ;
6
6
use async_trait:: async_trait;
7
7
pub use sea_query:: { Alias , CommonTableExpression , IntoTableRef , JoinType , UnionType , Value } ;
@@ -25,16 +25,33 @@ pub trait ModelTrait: Clone + Send + Debug {
25
25
R : EntityTrait ,
26
26
Self :: Entity : Related < R > ,
27
27
{
28
- <Self :: Entity as Related < R > >:: find_related ( ) . belongs_to ( self )
28
+ let mut select = Select :: < R > :: new ( ) ;
29
+ if let Some ( via) = <Self :: Entity as Related < R > >:: via ( ) {
30
+ select = select. join_rev ( JoinType :: InnerJoin , via)
31
+ }
32
+ select. find_by_relation ( <Self :: Entity as Related < R > >:: to ( ) , self , None )
29
33
}
30
34
31
35
/// Find linked Models
32
36
fn find_linked < L > ( & self , l : L ) -> Select < L :: ToEntity >
33
37
where
34
38
L : Linked < FromEntity = Self :: Entity > ,
35
39
{
36
- let tbl_alias = & format ! ( "r{}" , l. link( ) . len( ) - 1 ) ;
37
- l. find_linked ( ) . belongs_to_tbl_alias ( self , tbl_alias)
40
+ let mut link = l. link ( ) . into_iter ( ) . peekable ( ) ;
41
+ match link. next_if ( |rel| rel. on_condition . is_none ( ) ) {
42
+ Some ( last) => {
43
+ let tbl_alias = if link. len ( ) == 0 {
44
+ None
45
+ } else {
46
+ Some ( format ! ( "r{}" , link. len( ) - 1 ) )
47
+ } ;
48
+ find_linked ( link. rev ( ) , JoinType :: InnerJoin ) . find_by_relation ( last, self , tbl_alias)
49
+ }
50
+ None => {
51
+ let tbl_alias = & format ! ( "r{}" , link. len( ) - 1 ) ;
52
+ find_linked ( link. rev ( ) , JoinType :: InnerJoin ) . belongs_to_tbl_alias ( self , tbl_alias)
53
+ }
54
+ }
38
55
}
39
56
40
57
/// Find linked Models, recursively
0 commit comments