简体   繁体   English

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

[英]Create Composite Primary Key From Association in Sequelize

I have two models: Person and Team 我有两个模式: PersonTeam

Lets just say the models are simple (just assume basic string/int types): 可以说模型很简单(假设基本的字符串/整数类型):

team:
  id
  name
  ownerId

and

person:
  id
  name

I want to represent the associations between these two models such that a Person can belong to many Teams and a Team can belong to many Persons (ie a many to many relationship). 我想代表这两个模型之间的关联,以便一个人可以属于多个团队,一个团队可以属于多个人(即多对多关系)。

To do this is straight forward in Sequelize: 为此,在Sequelize中很简单:

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

This creates a new table called TeamPerson with both teamId and personId . 这将创建一个名为TeamPerson的新表,其中包含teamIdpersonId I assume the primary key of this table is a composite of both IDs. 我假设此表的主键是两个ID的组合。

I also want each team to have a captain: 我也希望每个团队都有一个队长:

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

This will add captainId to the Team model. 这会将captainId添加到团队模型。

Here is my issue, I want a Person to be able to create a Team, but I don't want them to be able to create two teams with the same name. 这是我的问题,我希望一个人能够创建一个团队,但是我不希望他们能够创建两个具有相同名称的团队。 I do, however, want to allow other Persons to create a team with the same name as other Persons. 但是,我确实希望允许其他人创建一个与其他人同名的团队。 So user ID 1 could not have two teams named "Falcons" but user ID 1 can have one team named "Falcons" and user ID 2 could have a team named "Falcons". 因此,用户ID 1不能有两个名为“ Falcons”的团队,但是用户ID 1可以有一个名为“ Falcons”的团队,而用户ID 2可以有一个名为“ Falcons”的团队。

Essentially the name and captainId should be a composite primary key on the Team table. 本质上,name和captainId应该是Team表上的复合主键。 Can anyone give me a tip as to how I might achieve this? 谁能给我一个小窍门,告诉我如何实现这一目标?

You could query for a previously existing person/project before allowing a new project to be created... roughly: 您可以在允许创建新项目之前查询以前存在的人/项目...大致:

    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)
            }
            ...

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

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