Sequelize, foreign keys as composite primary key

后端 未结 2 1305
陌清茗
陌清茗 2020-12-30 04:37

it is possible to define two foreign keys as a composite primary key of a model?

A user can only be a member of one family, a family can have many members and the fa

2条回答
  •  無奈伤痛
    2020-12-30 04:46

    In fact, almost I got the solution from documentation:

    User = sequelize.define('user', {});
    Project = sequelize.define('project', {});
    UserProjects = sequelize.define('userProjects', {
        status: DataTypes.STRING
    });
    
    User.belongsToMany(Project, { through: UserProjects });
    Project.belongsToMany(User, { through: UserProjects });
    

    By default the code above will add projectId and userId to the UserProjects table, and remove any previously defined primary key attribute - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns.

    Source

提交回复
热议问题