has-many.ejs
944 Bytes
var User = sequelize.define('User', {/* ... */})
var Project = sequelize.define('Project', {/* ... */})
// OK. Now things get more complicated (not really visible to the user :)).
// First let's define a hasMany association
Project.hasMany(User, {as: 'Workers'})
/*
This will add the attribute ProjectId or project_id to User.
Instances of Project will get the accessors getWorkers and setWorkers.
We could just leave it the way it is and let it be a one-way association.
But we want more! Let's define the other way around:
*/
User.hasMany(Project)
/*
This will remove the attribute ProjectId (or project_id) from User and create
a new model called ProjectsUsers with the equivalent foreign keys ProjectId
(or project_id) and UserId (or user_id). If the attributes are camelcase or
not depends on the Model it represents.
Now you can use Project#getWorkers, Project#setWorkers, User#getTasks and
User#setTasks.
*/