首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >relationMapping的Objection.js别名

relationMapping的Objection.js别名
EN

Stack Overflow用户
提问于 2020-06-23 14:58:23
回答 1查看 629关注 0票数 0

我有一个与Objection / Knex / Sql server的工作关系映射,当结果被分页时,它会导致问题。

代码语言:javascript
复制
components: {
        relation: BaseModel.HasManyRelation,
        modelClass: Component,
        join: {
            from: 'vehicle.id',
            to: 'component.vehicleID'
        }
    }

当我使用withGraphFetched获取每辆车的相关组件时,如果我在原始select中包含'vehicle.id‘,查询就会失败。

代码语言:javascript
复制
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’。

代码语言:javascript
复制
exec sp_executesql @statement=N'select count(*) as [count] from (select [id], [mark], [model], [id] from [vehicle]) as [temp]'

我的问题是,如何避免这种情况?我可以在关系映射中使用一些别名吗?我在关系映射中尝试了“vehicle.id as vehicleFK”,但这导致withGraphFetched根本不能运行。

EN

回答 1

Stack Overflow用户

发布于 2020-07-09 13:08:08

可能有两种方法可以尝试解决您的问题

  1. 摆脱组件的id列

代码语言:javascript
复制
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)
    }

  1. 使用objection中的ref函数引用表

中的id列

代码语言:javascript
复制
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)
}

...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62528999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档