簡體   English   中英

使用屬性對n:m關聯聯接表進行排序

[英]Sequelize n:m association join table with attributes

我正在嘗試使用Sequelize為Node JS中的an: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關聯! 我究竟做錯了什么? 感謝任何可以幫助我的人!

我找到了解決方案:做協會時我錯了。 在當前配置下,我只能索取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
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM