使用属性对n:m关联联接表进行排序

时间:2018-09-17 15:29:15

标签: mysql node.js sequelize.js

我正在尝试使用Sequelize为Node JS中的n:m关联建立模型。
以下图片显示了我要在后端映射的内容:

Imgur

使用官方文档,我定义的模型如下:

let Dashboards = sequelize.define('Dashboards', {
    name: DataType.STRING(30),
    category: DataType.TINYINT(2)
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboards'
});

Dashboards.associate = function (models) {
    Dashboards.belongsToMany(models.Charts, {
        through: {
            unique: false,
            model: models.DashboardCharts
        },
        foreignKey: 'dashboardId'
    });
};

let Charts = sequelize.define('Charts', {
    type: DataType.INTEGER(5),
    title: DataType.STRING(30),
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'charts'
});

Charts.associate = function (models) {
    Charts.belongsToMany(models.Dashboards, {
        through: {
            unique: false,
            model: models.DashboardCharts,
        },
        foreignKey: 'chartId'
    });
};
let DashboardCharts = sequelize.define('DashboardCharts', {
    title: {
        type: DataType.STRING(30)
    },
    color: {
        type: DataType.STRING(7)
    }
}, {
freezeTableName: true,
    timestamps: false,
    tableName: 'dashboard_charts'
});

现在,如果使用DashboardCharts,我尝试以这种方式将表与Dashboards连接起来:

DashboardCharts.findAll({
    include: [
        {
            model: Dashboard,
            required: true,
        }
    ]
})

我收到此错误: SequelizeEagerLoadingError:仪表板未与DashboardCharts关联! 我究竟做错了什么?感谢任何可以帮助我的人!

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:进行关联时我错了。在当前配置下,我只能索取Dashboard的图表,反之亦然。正确的解决方案是从联接表中设置belongsTo,如下所示:

let Dashboards = sequelize.define('Dashboards', {
    name: DataType.STRING(30),
    category: DataType.TINYINT(2)
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboards'
});

let Charts = sequelize.define('Charts', {
    type: DataType.INTEGER(5),
    title: DataType.STRING(30),
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'charts'
});


let DashboardCharts = sequelize.define('DashboardCharts', {
    dashboard_id: {
        type: DataType.INTEGER(5),
        primaryKey: true
    },
    chart_id: {
        type: DataType.INTEGER(5),
        primaryKey: true
    },
    title: {
        type: DataType.STRING(30)
    },
    color: {
        type: DataType.STRING(7)
    }
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboard_charts'
});

DashboardCharts.associate = function (models) {
    DashboardCharts.belongsTo(models.Dashboards, {
        foreignKey: 'dashboard_id',
        sourceKey: models.Dashboards.id
    });

    DashboardCharts.belongsTo(models.Charts, {
        foreignKey: 'chart_id',
        sourceKey: models.Charts.id
    });
};