Fix many-to-one

This commit is contained in:
Adria Navarro 2024-10-16 16:16:39 +02:00
parent 3fbe937bf4
commit b6874f52f6
1 changed files with 4 additions and 3 deletions

View File

@ -510,18 +510,19 @@ class InternalBuilder {
} }
}) })
} else { } else {
const toKey = `${toAlias}.${relationship.to}`
const foreignKey = `${fromAlias}.${relationship.from}` const foreignKey = `${fromAlias}.${relationship.from}`
// "join" to the main table, making sure the ID matches that of the main // "join" to the main table, making sure the ID matches that of the main
subQuery = subQuery.where( subQuery = subQuery.where(
`${toAlias}.${relationship.to}`, toKey,
"=", "=",
mainKnex.raw(this.quotedIdentifier(foreignKey)) mainKnex.raw(this.quotedIdentifier(foreignKey))
) )
query = query.where(q => { query = query.where(q => {
q.whereExists(whereCb(updatedKey, subQuery)) q.whereExists(whereCb(updatedKey, subQuery.clone()))
if (allowEmptyRelationships) { if (allowEmptyRelationships) {
q.orWhereNull(foreignKey) q.orWhereNotExists(subQuery)
} }
}) })
} }