嵌套的eager加载sequelize(belongsTo和belongsToMany在同一个查询中)

时间:2017-11-13 21:59:43

标签: mysql node.js express sequelize.js

在带有Express(4.15.2),Sequelize(3.30.0)和Mysql的NodeJS服务器(8.6.0)上, 我正面临着以下“简单”的用例: (不要注意表名;)) 我定义了这个模型:

Child.belongsTo(SON) Child.belongsToMany(父母)

tableName: 'Child',
classMethods: {
    associate: function(models) {
        this.belongsToMany(models.Parent, { as :{ singular: 'child',                 plural: 'children' }, through: 'Parent_Child'} );

        this.belongsTo(models.Son, {foreignKey : 'fkSon', as :'son' });
    }

我想在同一个查询中获取与Child相关的所有相关模型。 我的模型定义工作正常。我可以让父母与孩子和儿子有关,但不是两者都有。

此处我尝试运行的查询很遗憾(受sequelize doc http://docs.sequelizejs.com/manual/tutorial/models-usage.html#nested-eager-loading启发

models.Child.findAll({
include : [{model : models.Son, as:'son',
include : [{model : models.Parent, as : 'children', through:    'Parent_Child' , require : true}]

}]

我有以下错误:错误:父(子)与Son没有关联!

非常感谢提前:)

0 个答案:

没有答案