【问题标题】:Sequelize join table without selectingSequelize连接表而不选择
【发布时间】:2017-05-05 02:03:25
【问题描述】:

我想在 Sequelize 中以多对多关系从连接表中选择 ID,并根据其中一个端点限制结果。例如:

ModelA:
- id
- deleted_at
- is_expired

ModelB:
- id
- deleted_at
- is_active

ModelAToModelB:
- a_id
- b_id

我想做类似的事情

SELECT id FROM ModelAToModelB ab INNER JOIN ModelB b ON ab.b_id = b.id WHERE ab.id = someA_ID AND b.deleted_at IS NULL;

我目前正在做类似的事情

const ModelB = require("./modelb")
const ModelAToModelB = require("./modelatob");

ModelAToModelB.findAll({
    where: { id: someA_ID },
    include: [
       {
           model: ModelB,
           where: { deleted_at: null }
       }
    ]
})

这似乎可行,但我也从ModelB 获取所有数据,而我想要的只是ModelAToB.id

有什么方法可以废弃ModelB 的数据吗?或者也许使用来自 ModelA 的东西来获取关联 ID?

【问题讨论】:

    标签: javascript orm sequelize.js


    【解决方案1】:
    const ModelB = require("./modelb")
    const ModelAToModelB = require("./modelatob");
    
    ModelAToModelB.findAll({
        where: { id: someA_ID },
        include: [
           {
               model: ModelB.scope(null), //Prevent the default scope from adding attributes
               where: { deleted_at: null },
               required: true, //Force an inner join
               attributes: [] //Join without selecting any attributes
           }
        ]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 2016-09-17
      • 2021-12-19
      • 2018-08-24
      相关资源
      最近更新 更多