我有一个与Objection / Knex / Sql server的工作关系映射,当结果被分页时,它会导致问题。
components: {
relation: BaseModel.HasManyRelation,
modelClass: Component,
join: {
from: 'vehicle.id',
to: 'component.vehicleID'
}
}当我使用withGraphFetched获取每辆车的相关组件时,如果我在原始select中包含'vehicle.id‘,查询就会失败。
static getFieldList() {
return [
'id',
'mark',
'model'
].
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components')
.page(page, pagelength)
}现在,当分页完成时,Objection / Knex在第一个查询之后运行第二个查询,以获取总行数。Objection将关系映射中的'vehicle.id‘添加到查询中,从而导致查询失败,因为现在为子查询提取了两次列'id’。
exec sp_executesql @statement=N'select count(*) as [count] from (select [id], [mark], [model], [id] from [vehicle]) as [temp]'我的问题是,如何避免这种情况?我可以在关系映射中使用一些别名吗?我在关系映射中尝试了“vehicle.id as vehicleFK”,但这导致withGraphFetched根本不能运行。
发布于 2020-07-09 13:08:08
可能有两种方法可以尝试解决您的问题
const componentsSelectList = ()=>{
// select columns you need from components without the id column
return [
'column1', // columns you need
'column2'
]
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components',{minimize: true})
.modifyGraph('components',builder => builder.select(componentsSelectList()))
.page(page, pagelength)
}中的id列
const {ref} = require('objection')
...
static getFieldList() {
return [
ref('vehicle.id'),
'mark',
'model'
].
}
static getPagedList(page, pagelength) {
return this.query()
.select(this.getFieldList())
.withGraphFetched('components')
.page(page, pagelength)
}
...https://stackoverflow.com/questions/62528999
复制相似问题