Create constraint key with foreign keys sequelize

时间:2017-03-02 23:25:37

标签: mysql database database-design sequelize.js

I'm doing a relation between tables with sequelize but I have some troubles with it. First I have my Course model where I going to save all the relation between subject, periods etc.

module.exports = function(sequelize, DataTypes) {
  var Course = sequelize.define('Course', {
      ...
    },
    {
      associate: function(models){
        Course.hasMany(models.Schedule);

        Course.belongsTo(models.Period);
        Course.belongsTo(models.Room);
        Course.belongsTo(models.Subject);
      }
    }
  );

  return Course;
};

I was looking about Constraint Keys, and what I understood that with this I can have like restriction where I can't have the same combination on columns values through row. And also making easier to query later. So that means that add an extra column on the table? and how do I do that on sequelize with the foreign keys?

I looked on the sequelize documentation and what I found was use this code inside of the association of all columns that I need:

Course.belongsTo(models.Person, {foreignKey: {constraints: true}});

But that only makes to have unique values individually not between all.

I'm also using this property on my Schedule Model where I will save all the day and hours for the all Courses, and with that I pretend to block repeated rows, with different combination of day, and hours something like this "graph"

|  id  |     days     | starHr  |  endHr  |  idCourse  |
|  1   |    M,T,W     |  7:00   |  8:00   |      1     |
|  2   |    F,        |  8:00   |  9:00   |      1     |
|  3   |    Th        |  8:00   |  9:00   |      2     |
|  4   |    M,T,W     |  17:00  | 18:00   |      3     |

1 个答案:

答案 0 :(得分:0)

通过值在新表上定义。 您可以尝试制作具有唯一约束的复合索引

文档http://docs.sequelizejs.com/en/latest/docs/models-definition/#indexes

示例https://stackoverflow.com/a/42199137/4583460