繁体   English   中英

如何在 Sequelize 中建立多对多关系?

[英]How to do a Many to Many relationship in Sequelize?

这些是我的模型:员工

const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')

const Staff = sequelize.define('Staff', {

name: {
    type: DataTypes.STRING,
    allowNull: false,
},
SSN: {
    type: DataTypes.INTEGER,
},
email:{
    type: DataTypes.STRING,
}
}, {
    timestamps: true
});
Staff.associate = function (models) {
    Staff.belongsToMany(models.Technology, {through: models.StaffTechnology});

};

module.exports = Staff;

技术:

const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')


const Technology = sequelize.define('Technology', {
    name: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    description: {
        type: DataTypes.STRING,

    }
}, {
    timestamps: true
});
Technology.associate = function (models) {
    Technology.belongsToMany(models.Staff, { through: models.StaffTechnology});

};
module.exports = Technology;

这将是连接表:

const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')
const Staff = require('../../database/models/staff.model');
const Technology = require('../../database/models/technology.model');


const StaffTechnology = sequelize.define('StaffTechnology', {
    experience: {
        type: DataTypes.INTEGER,
    },
    StaffID: {
        type: DataTypes.INTEGER,
        references: {
            model: Staff, 
            key: 'id'
        }
    },
    TechnologyID: {
        type: DataTypes.INTEGER,
        references: {
            model: Technology,
            key: 'id'
        }
    },
}, {
    timestamps: true
});
StaffTechnology.associate = function (models) {
      //StaffTechnology.hasMany(models.Staff, { foreignKey: 'StaffID' });
      //StaffTechnology.hasMany(models.Technology, { foreignKey: 'TechnologyID' });
};

module.exports = StaffTechnology

现在我不能做 Staff.findAll({include:Technology}),因为它给我一个错误,说 Staff 和 Technology 没有关联,但我看到了 Sequelize 文档,我看到了一个非常相似的例子。 我想要的是返回 All Staffs 及其技术的可能性,Staff 可以拥有许多技术,而技术可以属于许多 Staffs,但实际上它们是通过 StaffTechnology 连接表连接的。

您需要在 index.js 中声明关联(或在您初始化数据库的位置)。 您可以通过要求模型并直接声明关联来手动完成

Model1.association(Model2, {
  through: "JoinTable"
}

Model2.association(Model1, {
  through: "JoinTable"
}

或者以编程方式执行(如果您已经在使用该方法来初始化您的数据库):

'use strict'
 
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = {
  "username": "root",
  "password": "YOUR ROOT PASSWORD HERE",
  "database": "YOUR DATABASE NAME HERE",
  "host": "127.0.0.1",
  "dialect": "mysql"
}
const db = {}
 
let sequelize = new Sequelize(config.database, config.username, config.password, config);
 
fs.readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0)
    && (file !== basename)
    && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });
 
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});
 
db.sequelize = sequelize;
db.Sequelize = Sequelize;
 
module.exports = db;

^ 此代码将初始化和关联合二为一。 您需要确保您的 model 文件和初始化文件在同一个文件夹中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM