File tree Expand file tree Collapse file tree 2 files changed +26
-8
lines changed
packages/drizzle/src/find Expand file tree Collapse file tree 2 files changed +26
-8
lines changed Original file line number Diff line number Diff line change 1
- import type { SQL } from 'drizzle-orm'
2
1
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
3
2
import type { SQLiteSelect , SQLiteSelectBase } from 'drizzle-orm/sqlite-core'
4
3
@@ -730,17 +729,24 @@ export const traverseFields = ({
730
729
const subQuery = query . as ( subQueryAlias )
731
730
732
731
if ( shouldCount ) {
732
+ let countSubquery : SQLiteSelect = db
733
+ . select ( selectFields as any )
734
+
735
+ . from ( newAliasTable )
736
+ . where ( subQueryWhere )
737
+ . $dynamic ( )
738
+
739
+ joins . forEach ( ( { type, condition, table } ) => {
740
+ countSubquery = countSubquery [ type ?? 'leftJoin' ] ( table , condition )
741
+ } )
742
+
733
743
currentArgs . extras [ `${ columnName } _count` ] = sql `${ db
734
744
. select ( {
735
745
count : count ( ) ,
736
746
} )
737
- . from (
738
- sql `${ db
739
- . select ( selectFields as any )
740
- . from ( newAliasTable )
741
- . where ( subQueryWhere )
742
- . as ( `${ subQueryAlias } _count_subquery` ) } `,
743
- ) } `. as ( `${ subQueryAlias } _count` )
747
+ . from ( sql `${ countSubquery . as ( `${ subQueryAlias } _count_subquery` ) } ` ) } `. as (
748
+ `${ subQueryAlias } _count` ,
749
+ )
744
750
}
745
751
746
752
currentArgs . extras [ columnName ] = sql `${ db
Original file line number Diff line number Diff line change @@ -215,6 +215,18 @@ describe('Joins Field', () => {
215
215
expect ( categoryWithPosts . group . relatedPosts ?. totalDocs ) . toBe ( 15 )
216
216
} )
217
217
218
+ it ( 'should count hasMany relationship joins' , async ( ) => {
219
+ const res = await payload . findByID ( {
220
+ id : category . id ,
221
+ collection : categoriesSlug ,
222
+ joins : {
223
+ hasManyPosts : { limit : 1 , count : true } ,
224
+ } ,
225
+ } )
226
+
227
+ expect ( res . hasManyPosts ?. totalDocs ) . toBe ( 15 )
228
+ } )
229
+
218
230
it ( 'should populate relationships in joins' , async ( ) => {
219
231
const { docs } = await payload . find ( {
220
232
limit : 1 ,
You can’t perform that action at this time.
0 commit comments