Nested relation childs count
I have a base query variable which is growing according to request params
let query = Client.query()
.withGraphFetched(
'[documents.[files], loans(onlyActiveLoansByMfo).[documents.[files]]]',
)
.modifiers({
onlyActiveLoansByMfo(builder) {
builder.whereIn('filialCode', mfos).andWhere('condition', '1')
},
})
like this
if (user.mfoAccesses.length !== 0 && mfos.length !== allMfos.length) {
// Hasn't access to all mfos
query = query.whereExists(
Client.relatedQuery('accounts')
.whereIn('filialCode', mfos)
.andWhere('number', 'like', '202%')
.andWhere(function() {
this.where('status', 'M').orWhere('status', 'O')
}),
)
const ClientDocument = require('~root/models/clientDocument')
if (params.withStatistic) {
statistic.clientDocumentsTotal = await ClientDocument.query().whereIn('clientCode', mfos)
.andWhere('condition', '1').count()
statistic.loanDocumentFilesTotal = await Loan.relatedQuery('documents').whereIn('filialCode', mfos)
.andWhere('condition', '1').whereExists().count()
}
}
at the end of this code I have unfinished queries where I want to get all clients (of above query) documents total amount and total amount of documents with files.
my relations schema: client has many documents and loans, documents and loans has many to many files relationship
Cool, looks good.
Cool, looks good.
@koskimas can you help me with a query? I need to count client and loan documents total and also them which have files. clients also have hasMany loans relation
I don't understand what you are after. I can't help if you can't explain the problem better.
I have clients query
Client.query().whereExists(
Client.relatedQuery('accounts')
.whereIn('filialCode', mfos)
.andWhere('number', 'like', '202%')
.andWhere(function() {
this.where('status', 'M').orWhere('status', 'O')
})
I want to get these clients related documents without and with files total count. Not separately for each client, but the total. Same for loans which also have documents relation
I still don't know if I understood, but how about this?
const clientsQuery = Client.query().whereExists(
Client.relatedQuery('accounts')
.whereIn('filialCode', mfos)
.andWhere('number', 'like', '202%')
.andWhere(function() {
this.where('status', 'M').orWhere('status', 'O')
})
)
statistic.loanDocumentFilesTotal = await Client.relatedQuery('documents').for(clientsQuery).count()
@koskimas oh, yes, that's exactly what is needed
@koskimas Now I have this, but there's a problem with performance when I'm adding this condition to relatedQuery
.whereExists(ClientLoanDocument.relatedQuery('files'))
In the console you can see that performance degrades about 10 times

@koskimas same thing here when I'm trying to delete documents through loansQuery with condition.
is it possible to reduce the query completion time?

You probably don't have the needed indexes.