Reputation: 339
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 (i.e. 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?
Upvotes: 0
Views: 611
Reputation: 1968
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)
}
...
Upvotes: 1