【问题标题】:Is it possible add extra field in Sequelize relation?是否可以在 Sequelize 关系中添加额外的字段?
【发布时间】:2017-02-16 04:33:31
【问题描述】:

我有这样的belongsTo 关系:

classMethods: {
    associate: function(models) {
        User.belongsTo(models.Prefs, {timestamps: false, foreignKey: 'Type', targetKey: 'UserType'})

    }
}

产生

 LEFT OUTER JOIN `prefs` AS `Prefs` ON `User`.`Type` = `Prefs`.`UserType`

问题是我还需要添加额外的检查,例如

AND `Prefs`.`Section` = 'GLOBAL'

有可能吗?

【问题讨论】:

    标签: mysql sequelize.js


    【解决方案1】:

    我相信这是 Sequelize - Join with multiple column 的重复。

    您需要在JOIN 子句中使用自定义ON 条件

    User.findAll({
        include: [
            {
                model: Prefs,
                on: {
                    Type: db.sequelize.where(db.sequelize.col("User.Type"), "=", db.sequelize.col("Prefs.UserType")),
                    Section: 'GLOBAL'
                },
                attributes: [] // do not return any columns of Prefs table
            }
        ]
    }).then((users) => {
        // resulting users...
    });
    

    编辑

    我相信scope 就是您要找的。尝试将其添加到关联中

    classMethods: {
        associate: function(models) {
            User.belongsTo(
                models.Prefs,
                {
                    timestamps: false,
                    foreignKey: 'Type',
                    targetKey: 'UserType',
                    scope: { Section: 'GLOBAL' }
                }
            );
        }    
    }
    

    【讨论】:

    • 我需要在模型类中指定这个
    • 我更新了答案,希望这个对你有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2010-11-12
    • 2018-09-11
    • 2016-10-26
    相关资源
    最近更新 更多