From 9e4e7cee1209b57bfb12183e1d010b15615d63b3 Mon Sep 17 00:00:00 2001 From: kiddyu <58631254@qq.com> Date: Tue, 14 May 2024 21:14:01 +0800 Subject: [PATCH] fix: `belongsToMany` relation withCount --- src/relations/belongs-to-many.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/relations/belongs-to-many.js b/src/relations/belongs-to-many.js index 5fc33d7..9267487 100644 --- a/src/relations/belongs-to-many.js +++ b/src/relations/belongs-to-many.js @@ -300,6 +300,27 @@ class BelongsToMany extends compose( // this.touch(); // } // } + + getRelationExistenceQuery(query, parentQuery, columns = ['*']) { + if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) { + return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns); + } + + this.performJoin(query); + + return super.getRelationExistenceQuery(query, parentQuery, columns); + } + + getRelationExistenceQueryForSelfJoin(query, parentQuery, columns = ['*']) { + const hash = this.getRelationCountHash(); + query.select(columns).from(this.related.getTable() + ' as ' + hash); + + this.related.setTable(hash); + + this.performJoin(query); + + return super.getRelationExistenceQuery(query, parentQuery, columns); + } } module.exports = BelongsToMany; \ No newline at end of file