@@ -1292,25 +1292,29 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {
12921292 const fieldModel = fieldDef . type as GetModels < Schema > ;
12931293 let fieldCountQuery : SelectQueryBuilder < any , any , any > ;
12941294
1295+ // Use a unique alias for the subquery to avoid ambiguous references when
1296+ // fieldModel === model (self-referential relation on a delegate model)
1297+ const subQueryAlias = tmpAlias ( `${ parentAlias } $_${ field } $count` ) ;
1298+
12951299 // join conditions
12961300 const m2m = getManyToManyRelation ( this . schema , model , field ) ;
12971301 if ( m2m ) {
12981302 // many-to-many relation, count the join table
1299- fieldCountQuery = this . buildModelSelect ( fieldModel , fieldModel , value as any , false )
1303+ fieldCountQuery = this . buildModelSelect ( fieldModel , subQueryAlias , value as any , false )
13001304 . innerJoin ( m2m . joinTable , ( join ) =>
13011305 join
1302- . onRef ( `${ m2m . joinTable } .${ m2m . otherFkName } ` , '=' , `${ fieldModel } .${ m2m . otherPKName } ` )
1306+ . onRef ( `${ m2m . joinTable } .${ m2m . otherFkName } ` , '=' , `${ subQueryAlias } .${ m2m . otherPKName } ` )
13031307 . onRef ( `${ m2m . joinTable } .${ m2m . parentFkName } ` , '=' , `${ parentAlias } .${ m2m . parentPKName } ` ) ,
13041308 )
13051309 . select ( eb . fn . countAll ( ) . as ( `_count$${ field } ` ) ) ;
13061310 } else {
13071311 // build a nested query to count the number of records in the relation
1308- fieldCountQuery = this . buildModelSelect ( fieldModel , fieldModel , value as any , false ) . select (
1312+ fieldCountQuery = this . buildModelSelect ( fieldModel , subQueryAlias , value as any , false ) . select (
13091313 eb . fn . countAll ( ) . as ( `_count$${ field } ` ) ,
13101314 ) ;
13111315
13121316 // join conditions
1313- const joinPairs = buildJoinPairs ( this . schema , model , parentAlias , field , fieldModel ) ;
1317+ const joinPairs = buildJoinPairs ( this . schema , model , parentAlias , field , subQueryAlias ) ;
13141318 for ( const [ left , right ] of joinPairs ) {
13151319 fieldCountQuery = fieldCountQuery . whereRef ( left , '=' , right ) ;
13161320 }
0 commit comments