从Sequelize中的关联创建复合主键

时间:2019-03-05 20:30:33

标签: javascript sql orm sequelize.js

我有两个模型:PersonTeam

让我们说模型很简单(假设基本的字符串/整数类型):

team:
  id
  name
  ownerId

person:
  id
  name

我想表示这两个模型之间的关联,以便一个人可以属于多个团队,一个团队可以属于多个人(即多对多关系)。

在Sequelize中直接做到这一点:

Team.belongsToMany(Person, {through: 'TeamPerson'})
Person.belongsToMany(Team, {through: 'TeamPerson'})

这将创建一个名为TeamPerson的新表,其中同时包含teamIdpersonId。我假设此表的主键是两个ID的组合。

我也希望每个团队都有一个队长:

Team.belongsTo(Person {as: 'captain'})

这会将captainId添加到团队模型。

这是我的问题,我希望一个人能够创建一个团队,但我不希望他们能够创建两个具有相同名称的团队。但是,我确实希望允许其他人创建一个与其他人同名的团队。因此,用户ID 1不能有两个名为“ Falcons”的团队,但是用户ID 1可以有一个名为“ Falcons”的团队,而用户ID 2可以有一个名为“ Falcons”的团队。

基本上,名称和captainId应该是Team表上的复合主键。谁能给我一个小窍门,告诉我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以在允许创建新项目之前查询以前存在的人/项目...大致:

    Person.findAll({
        attributes: ['id'],
        include: [{
            model: Team,
            where : { name : ***TEAM_NAME_PARAM*** }
            attributes: [
                [Sequelize.fn('count', 'id'), 'number_of_teams']
           ]
        }],
        where: { id : ***USER_ID_PARAM***},
        group: ['id']
        })        
        .then(myTeams => {
            if (myTeams.length == 0 || myTeams.Team.number_of_teams == 0) {
               // proceed with creating new team
            } else {
               // give some error message (you already have a team with that name)
            }
            ...