简体   繁体   中英

Create Composite Primary Key From Association in Sequelize

I have two models: Person and Team

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:

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

This creates a new table called TeamPerson with both teamId and personId . I assume the primary key of this table is a composite of both IDs.

I also want each team to have a captain:

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

This will add captainId to the Team model.

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".

Essentially the name and captainId should be a composite primary key on the Team table. 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)
            }
            ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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