@@ -54,7 +54,7 @@ public function getSelectFields(): ImmutableArray
5454 ->map (map: fn (
5555 $ field ,
5656 ) => new FieldStatement (
57- field: $ targetModel ->getTableName () . '. ' . $ field ,
57+ field: $ this -> getTableAlias (tableName: $ targetModel ->getTableName () ) . '. ' . $ field ,
5858 )
5959 ->withAlias (
6060 alias: sprintf (
@@ -120,7 +120,6 @@ public function getJoinStatement(): JoinStatement
120120 ownerModel: $ ownerModel ,
121121 targetModel: $ targetModel ,
122122 );
123-
124123 return new JoinStatement (
125124 statement: sprintf (
126125 '%s %s ' ,
@@ -131,6 +130,7 @@ public function getJoinStatement(): JoinStatement
131130 $ this ->buildSecondJoin (
132131 targetModel: $ targetModel ,
133132 pivotTable: $ pivotTable ,
133+ tableAlias: $ this ->getTableAlias (tableName: $ targetModel ->getTableName ()),
134134 ),
135135 ),
136136 );
@@ -174,11 +174,20 @@ private function buildFirstJoin(
174174 private function buildSecondJoin (
175175 ModelInspector $ targetModel ,
176176 string $ pivotTable ,
177+ string $ tableAlias ,
177178 ): string {
179+ $ tableName = $ targetModel ->getTableName ();
180+ $ tableRef = $ tableAlias !== $ tableName
181+ ? sprintf ('%s AS %s ' , $ tableName , $ tableAlias )
182+ : $ tableName ;
183+
178184 return sprintf (
179185 'LEFT JOIN %s ON %s = %s ' ,
180- $ targetModel ->getTableName (),
181- $ this ->resolveRelatedRelationJoin (targetModel: $ targetModel ),
186+ $ tableRef ,
187+ $ this ->resolveRelatedRelationJoin (
188+ targetModel: $ targetModel ,
189+ tableAlias: $ tableAlias ,
190+ ),
182191 $ this ->resolveRelatedOwnerJoin (
183192 targetModel: $ targetModel ,
184193 pivotTable: $ pivotTable ,
@@ -316,7 +325,7 @@ private function resolveRelatedOwnerJoin(
316325 /**
317326 * PK on target: target.id
318327 */
319- private function resolveRelatedRelationJoin (ModelInspector $ targetModel ): string
328+ private function resolveRelatedRelationJoin (ModelInspector $ targetModel, string $ tableAlias ): string
320329 {
321330 $ relatedRelationJoin = $ this ->relatedRelationJoin ;
322331
@@ -329,7 +338,7 @@ private function resolveRelatedRelationJoin(ModelInspector $targetModel): string
329338 ) {
330339 return sprintf (
331340 '%s.%s ' ,
332- $ targetModel -> getTableName () ,
341+ $ tableAlias ,
333342 $ relatedRelationJoin ,
334343 );
335344 }
@@ -349,8 +358,17 @@ private function resolveRelatedRelationJoin(ModelInspector $targetModel): string
349358
350359 return sprintf (
351360 '%s.%s ' ,
352- $ targetModel -> getTableName () ,
361+ $ tableAlias ,
353362 $ primaryKey ,
354363 );
355364 }
365+
366+ private function getTableAlias (string $ tableName ): string
367+ {
368+ if ($ this ->parent === null || $ this ->parent === '' ) {
369+ return $ tableName ;
370+ }
371+
372+ return str (string: $ this ->parent )->replace ('. ' , '_ ' )->append ('_ ' , $ this ->property ->getName ())->toString ();
373+ }
356374}
0 commit comments