如何编写可能来自不同表的“属于”关联?

时间:2019-05-15 04:36:14

标签: sql database sequelize.js sequelize-cli

如何为属于模型B或模型C但不同时属于两者的模型A编写关联?

说我有一个员工模型,承包商模型和事件模型。关联如下: 员工有很多活动。
承包商有很多活动。
事件属于承包商或雇员。

我是否创建联接表employee_contractor,并说事件属于employee_contractor?

这可能是微不足道的,但是对于Sequelize / DB编程来说却是很新的东西,我很难理解什么时候使用什么。我知道那里可能存在此类问题的答案,但我不知道用什么语言正确地表达我的问题以找到答案。

// Employee model
'use strict';
module.exports = (sequelize, DataTypes) => {
  const Employee = sequelize.define('Employee', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    // other fields
    //...

  }, {});
  Employee.associate = function(models) {
    // associations can be defined here
  };
  return Employee;
};
// Contractor model
'use strict';
module.exports = (sequelize, DataTypes) => {
  const Contractor = sequelize.define('Contractor', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    company: DataTypes.STRING,
    // other fields
    //...

  }, {});
  Contractor.associate = function(models) {
    // associations can be defined here
  };
  return Contractor;
};
// Event Model
'use strict';
module.exports = (sequelize, DataTypes) => {
  const Event = sequelize.define('Event', {
    reason: DataTypes.STRING,
    escort: DataTypes.STRING,
    // other fields
    //...

  }, {});
  Event.associate = function(models) {
    // associations can be defined here
  };
  return Event;
};

1 个答案:

答案 0 :(得分:0)

在这种情况下,我建议将事件分为两个不同的事件:employeeEventsContractorEvents(以便在以后的查询操作中更容易利用序列化关联),并使用简单的{{1 }}上的每种事件,belongsTo上的参与者。

hasMany

Employee

// Employee model 'use strict'; module.exports = (sequelize, DataTypes) => { const Employee = sequelize.define('Employee', { firstName: DataTypes.STRING, lastName: DataTypes.STRING, // other fields //... }, {}); Employee.associate = function(models) { // associations can be defined here Employee.hasMany(models.EmployeeEvent); }; return Employee; };

EmployeeEvents

// EmployeeEvent Model 'use strict'; module.exports = (sequelize, DataTypes) => { const EmployeeEvent = sequelize.define('Event', { reason: DataTypes.STRING, escort: DataTypes.STRING, // other fields //... }, {}); EmployeeEvent.associate = function(models) { // associations can be defined here EmployeeEvent.belongsTo(models.Employee); }; return EmployeeEvent; };

Contractor

// Contractor model 'use strict'; module.exports = (sequelize, DataTypes) => { const Contractor = sequelize.define('Contractor', { firstName: DataTypes.STRING, lastName: DataTypes.STRING, company: DataTypes.STRING, // other fields //... }, {}); Contractor.associate = function(models) { // associations can be defined here Contractor.hasMany(models.ContractorEvent); }; return Contractor; };

ContractorEvents