Getting through join working as expected.
This commit is contained in:
parent
49c1f34b5d
commit
628964364a
|
@ -345,6 +345,7 @@ class InternalBuilder {
|
||||||
const mainKnex = this.knex
|
const mainKnex = this.knex
|
||||||
const { relationships, endpoint, tableAliases: aliases } = this.query
|
const { relationships, endpoint, tableAliases: aliases } = this.query
|
||||||
const tableName = endpoint.entityId
|
const tableName = endpoint.entityId
|
||||||
|
const fromAlias = aliases?.[tableName] || tableName
|
||||||
if (!relationships) {
|
if (!relationships) {
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
@ -356,22 +357,37 @@ class InternalBuilder {
|
||||||
relationship.tableName
|
relationship.tableName
|
||||||
) {
|
) {
|
||||||
const relatedTableName = relationship.tableName
|
const relatedTableName = relationship.tableName
|
||||||
const alias = aliases?.[relatedTableName] || relatedTableName
|
const toAlias = aliases?.[relatedTableName] || relatedTableName
|
||||||
let subQuery = mainKnex
|
let subQuery = mainKnex
|
||||||
.select(mainKnex.raw(1))
|
.select(mainKnex.raw(1))
|
||||||
.from({ [alias]: relatedTableName })
|
.from({ [toAlias]: relatedTableName })
|
||||||
subQuery = whereCb(
|
let mainTableRelatesTo = toAlias
|
||||||
this.addJoin(
|
if (relationship.through) {
|
||||||
subQuery,
|
const throughAlias =
|
||||||
{
|
aliases?.[relationship.through] || relationship.through
|
||||||
from: relationship.tableName,
|
let throughTable = this.tableNameWithSchema(relationship.through, {
|
||||||
to: tableName,
|
alias: throughAlias,
|
||||||
through: relationship.through,
|
schema: endpoint.schema,
|
||||||
},
|
})
|
||||||
[relationship]
|
subQuery = subQuery.innerJoin(throughTable, function () {
|
||||||
|
// @ts-ignore
|
||||||
|
this.orOn(
|
||||||
|
`${toAlias}.${relationship.toPrimary}`,
|
||||||
|
"=",
|
||||||
|
`${throughAlias}.${relationship.to}`
|
||||||
|
)
|
||||||
|
})
|
||||||
|
mainTableRelatesTo = throughAlias
|
||||||
|
}
|
||||||
|
// "join" to the main table, making sure the ID matches that of the main
|
||||||
|
subQuery = subQuery.where(
|
||||||
|
`${mainTableRelatesTo}.${relationship.from}`,
|
||||||
|
"=",
|
||||||
|
mainKnex.raw(
|
||||||
|
this.quotedIdentifier(`${fromAlias}.${relationship.fromPrimary}`)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
query = query.whereExists(subQuery)
|
query = query.whereExists(whereCb(subQuery))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue