Associations

This section describes the various association types in sequelize. When calling a method such as User.hasOne(Project), we say that the User model (the model that the function is being invoked on) is the source and the Project model (the model being passed as an argument) is the target.

One-To-One associations

One-To-One associations are associations between exactly two models connected by a single foreign key.

BelongsTo

BelongsTo associations are associations where the foreign key for the one-to-one relation exists on the source model.

A simple example would be a Player being part of a Team with the foreign key on the player.

  1. const Player = this.sequelize.define('player', {/* attributes */});
  2. const Team = this.sequelize.define('team', {/* attributes */});
  3. Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team

Foreign keys

By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.

The default casing is camelCase however if the source model is configured with underscored: true the foreignKey will be snake_case.

  1. const User = this.sequelize.define('user', {/* attributes */})
  2. const Company = this.sequelize.define('company', {/* attributes */});
  3. User.belongsTo(Company); // Will add companyId to user
  4. const User = this.sequelize.define('user', {/* attributes */}, {underscored: true})
  5. const Company = this.sequelize.define('company', {
  6. uuid: {
  7. type: Sequelize.UUID,
  8. primaryKey: true
  9. }
  10. });
  11. User.belongsTo(Company); // Will add company_uuid to user

In cases where as has been defined it will be used in place of the target model name.

  1. const User = this.sequelize.define('user', {/* attributes */})
  2. const UserRole = this.sequelize.define('userRole', {/* attributes */});
  3. User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId

In all cases the default foreign key can be overwritten with the foreignKey option.When the foreign key option is used, Sequelize will use it as-is:

  1. const User = this.sequelize.define('user', {/* attributes */})
  2. const Company = this.sequelize.define('company', {/* attributes */});
  3. User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User

Target keys

The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the targetKey option.

  1. const User = this.sequelize.define('user', {/* attributes */})
  2. const Company = this.sequelize.define('company', {/* attributes */});
  3. User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User

HasOne

HasOne associations are associations where the foreign key for the one-to-one relation exists on the target model.

  1. const User = sequelize.define('user', {/* ... */})
  2. const Project = sequelize.define('project', {/* ... */})
  3. // One-way associations
  4. Project.hasOne(User)
  5. /*
  6. In this example hasOne will add an attribute projectId to the User model!
  7. Furthermore, Project.prototype will gain the methods getUser and setUser according
  8. to the first parameter passed to define. If you have underscore style
  9. enabled, the added attribute will be project_id instead of projectId.
  10. The foreign key will be placed on the users table.
  11. You can also define the foreign key, e.g. if you already have an existing
  12. database and want to work on it:
  13. */
  14. Project.hasOne(User, { foreignKey: 'initiator_id' })
  15. /*
  16. Because Sequelize will use the model's name (first parameter of define) for
  17. the accessor methods, it is also possible to pass a special option to hasOne:
  18. */
  19. Project.hasOne(User, { as: 'Initiator' })
  20. // Now you will get Project.getInitiator and Project.setInitiator
  21. // Or let's define some self references
  22. const Person = sequelize.define('person', { /* ... */})
  23. Person.hasOne(Person, {as: 'Father'})
  24. // this will add the attribute FatherId to Person
  25. // also possible:
  26. Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'})
  27. // this will add the attribute DadId to Person
  28. // In both cases you will be able to do:
  29. Person.setFather
  30. Person.getFather
  31. // If you need to join a table twice you can double join the same table
  32. Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'});
  33. Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'});
  34. Game.belongsTo(Team);

Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.

Difference between HasOne and BelongsTo

In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are suitable for different scenarios. Lets study this difference using an example.

Suppose we have two tables to link Player and Team. Lets define their models.

  1. const Player = this.sequelize.define('player', {/* attributes */})
  2. const Team = this.sequelize.define('team', {/* attributes */});

When we link two models in Sequelize we can refer them as pairs of source and target models. Like this

Having Player as the source and Team as the target

  1. Player.belongsTo(Team);
  2. //Or
  3. Player.hasOne(Team);

Having Team as the source and Player as the target

  1. Team.belongsTo(Player);
  2. //Or
  3. Team.hasOne(Player);

HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in target model whereas BelongsTo inserts the association key in the source model.

Here is an example demonstrating use cases of BelongsTo and HasOne.

  1. const Player = this.sequelize.define('player', {/* attributes */})
  2. const Coach = this.sequelize.define('coach', {/* attributes */})
  3. const Team = this.sequelize.define('team', {/* attributes */});

Suppose our Player model has information about its team as teamId column. Information about each Team's Coach is stored in the Team model as coachId column. These both scenarios requires different kind of 1:1 relation because foreign key relation is present on different models each time.

When information about association is present in source model we can use belongsTo. In this case Player is suitable for belongsTo because it has teamId column.

  1. Player.belongsTo(Team) // `teamId` will be added on Player / Source model

When information about association is present in target model we can use hasOne. In this case Coach is suitable for hasOne because Team model store information about its Coach as coachId field.

  1. Coach.hasOne(Team) // `coachId` will be added on Team / Target model

One-To-Many associations (hasMany)

One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.

  1. const User = sequelize.define('user', {/* ... */})
  2. const Project = sequelize.define('project', {/* ... */})
  3. // OK. Now things get more complicated (not really visible to the user :)).
  4. // First let's define a hasMany association
  5. 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.

Sometimes you may need to associate records on different columns, you may use sourceKey option:

  1. const City = sequelize.define('city', { countryCode: Sequelize.STRING });
  2. const Country = sequelize.define('country', { isoCode: Sequelize.STRING });
  3. // Here we can connect countries and cities base on country code
  4. Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
  5. City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});

So far we dealt with a one-way association. But we want more! Let's define it the other way around by creating a many to many association in the next section.

Belongs-To-Many associations

Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.

  1. Project.belongsToMany(User, {through: 'UserProject'});
  2. User.belongsToMany(Project, {through: 'UserProject'});

This will create a new model called UserProject with the equivalent foreign keys projectId and userId. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).

Defining through is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.

This will add methods getUsers, setUsers, addUser,addUsers to Project, and getProjects, setProjects, addProject, and addProjects to User.

Sometimes you may want to rename your models when using them in associations. Let's define users as workers and projects as tasks by using the alias (as) option. We will also manually define the foreign keys to use:

  1. User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId' })
  2. Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })

foreignKey will allow you to set source model key in the through relation.otherKey will allow you to set target model key in the through relation.

  1. User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId', otherKey: 'projectId'})

Of course you can also define self references with belongsToMany:

  1. Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
  2. // This will create the table PersonChildren which stores the ids of the objects.

If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:

  1. const User = sequelize.define('user', {})
  2. const Project = sequelize.define('project', {})
  3. const UserProjects = sequelize.define('userProjects', {
  4. status: DataTypes.STRING
  5. })
  6. User.belongsToMany(Project, { through: UserProjects })
  7. Project.belongsToMany(User, { through: UserProjects })

To add a new project to a user and set its status, you pass extra options.through to the setter, which contains the attributes for the join table

  1. user.addProject(project, { through: { status: 'started' }})

By default the code above will add projectId and userId to the UserProjects table, and remove any previously defined primary key attribute - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the UserProjects model you can add it manually.

  1. const UserProjects = sequelize.define('userProjects', {
  2. id: {
  3. type: Sequelize.INTEGER,
  4. primaryKey: true,
  5. autoIncrement: true
  6. },
  7. status: DataTypes.STRING
  8. })

With Belongs-To-Many you can query based on through relation and select specific attributes. For example using findAll with through

  1. User.findAll({
  2. include: [{
  3. model: Project,
  4. through: {
  5. attributes: ['createdAt', 'startedAt', 'finishedAt'],
  6. where: {completed: true}
  7. }
  8. }]
  9. });

Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using uniqueKey option.

  1. Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })

Scopes

This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see Scopes.

Association scopes allow you to place a scope (a set of default attributes for get and create) on the association. Scopes can be placed both on the associated model (the target of the association), and on the through table for n:m relations.

1:m

Assume we have tables Comment, Post, and Image. A comment can be associated to either an image or a post via commentable_id and commentable - we say that Post and Image are Commentable

  1. const Comment = this.sequelize.define('comment', {
  2. title: Sequelize.STRING,
  3. commentable: Sequelize.STRING,
  4. commentable_id: Sequelize.INTEGER
  5. });
  6. Comment.prototype.getItem = function(options) {
  7. return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options);
  8. };
  9. Post.hasMany(this.Comment, {
  10. foreignKey: 'commentable_id',
  11. constraints: false,
  12. scope: {
  13. commentable: 'post'
  14. }
  15. });
  16. Comment.belongsTo(this.Post, {
  17. foreignKey: 'commentable_id',
  18. constraints: false,
  19. as: 'post'
  20. });
  21. Image.hasMany(this.Comment, {
  22. foreignKey: 'commentable_id',
  23. constraints: false,
  24. scope: {
  25. commentable: 'image'
  26. }
  27. });
  28. Comment.belongsTo(this.Image, {
  29. foreignKey: 'commentable_id',
  30. constraints: false,
  31. as: 'image'
  32. });

constraints: false, disables references constraints - since the commentable_id column references several tables, we cannot add a REFERENCES constraint to it. Note that the Image -> Comment and Post -> Comment relations define a scope, commentable: 'image' and commentable: 'post' respectively. This scope is automatically applied when using the association functions:

  1. image.getComments()
  2. SELECT * FROM comments WHERE commentable_id = 42 AND commentable = 'image';
  3. image.createComment({
  4. title: 'Awesome!'
  5. })
  6. INSERT INTO comments (title, commentable_id, commentable) VALUES ('Awesome!', 42, 'image');
  7. image.addComment(comment);
  8. UPDATE comments SET commentable_id = 42, commentable = 'image'

The getItem utility function on Comment completes the picture - it simply converts the commentable string into a call to either getImage or getPost, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to getItem(options) to specify any where conditions or includes.

n:m

Continuing with the idea of a polymorphic model, consider a tag table - an item can have multiple tags, and a tag can be related to several items.

For brevity, the example only shows a Post model, but in reality Tag would be related to several other models.

  1. const ItemTag = sequelize.define('item_tag', {
  2. id : {
  3. type: DataTypes.INTEGER,
  4. primaryKey: true,
  5. autoIncrement: true
  6. },
  7. tag_id: {
  8. type: DataTypes.INTEGER,
  9. unique: 'item_tag_taggable'
  10. },
  11. taggable: {
  12. type: DataTypes.STRING,
  13. unique: 'item_tag_taggable'
  14. },
  15. taggable_id: {
  16. type: DataTypes.INTEGER,
  17. unique: 'item_tag_taggable',
  18. references: null
  19. }
  20. });
  21. const Tag = sequelize.define('tag', {
  22. name: DataTypes.STRING
  23. });
  24. Post.belongsToMany(Tag, {
  25. through: {
  26. model: ItemTag,
  27. unique: false,
  28. scope: {
  29. taggable: 'post'
  30. }
  31. },
  32. foreignKey: 'taggable_id',
  33. constraints: false
  34. });
  35. Tag.belongsToMany(Post, {
  36. through: {
  37. model: ItemTag,
  38. unique: false
  39. },
  40. foreignKey: 'tag_id',
  41. constraints: false
  42. });

Notice that the scoped column (taggable) is now on the through model (ItemTag).

We could also define a more restrictive association, for example, to get all pending tags for a post by applying a scope of both the through model (ItemTag) and the target model (Tag):

  1. Post.hasMany(Tag, {
  2. through: {
  3. model: ItemTag,
  4. unique: false,
  5. scope: {
  6. taggable: 'post'
  7. }
  8. },
  9. scope: {
  10. status: 'pending'
  11. },
  12. as: 'pendingTags',
  13. foreignKey: 'taggable_id',
  14. constraints: false
  15. });
  16. Post.getPendingTags();
  1. SELECT `tag`.* INNER JOIN `item_tags` AS `item_tag`
  2. ON `tag`.`id` = `item_tag`.`tagId`
  3. AND `item_tag`.`taggable_id` = 42
  4. AND `item_tag`.`taggable` = 'post'
  5. WHERE (`tag`.`status` = 'pending');

constraints: false disables references constraints on the taggable_id column. Because the column is polymorphic, we cannot say that it REFERENCES a specific table.

Naming strategy

By default sequelize will use the model name (the name passed to sequelize.define) to figure out the name of the model when used in associations. For example, a model named user will add the functions get/set/add User to instances of the associated model, and a property named .user in eager loading, while a model named User will add the same functions, but a property named .User (notice the upper case U) in eager loading.

As we've already seen, you can alias models in associations using as. In single associations (has one and belongs to), the alias should be singular, while for many associations (has many) it should be plural. Sequelize then uses the inflection library to convert the alias to its singular form. However, this might not always work for irregular or non-english words. In this case, you can provide both the plural and the singular form of the alias:

  1. User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }})
  2. // Notice that inflection has no problem singularizing tasks, this is just for illustrative purposes.

If you know that a model will always use the same alias in associations, you can provide it when creating the model

  1. const Project = sequelize.define('project', attributes, {
  2. name: {
  3. singular: 'task',
  4. plural: 'tasks',
  5. }
  6. })
  7. User.belongsToMany(Project);

This will add the functions add/set/get Tasks to user instances.

Remember, that using as to change the name of the association will also change the name of the foreign key. When using as, it is safest to also specify the foreign key.

  1. Invoice.belongsTo(Subscription)
  2. Subscription.hasMany(Invoice)

Without as, this adds subscriptionId as expected. However, if you were to say Invoice.belongsTo(Subscription, { as: 'TheSubscription' }), you will have both subscriptionId and theSubscriptionId, because sequelize is not smart enough to figure that the calls are two sides of the same relation. 'foreignKey' fixes this problem;

  1. Invoice.belongsTo(Subscription, , { as: 'TheSubscription', foreignKey: 'subscription_id' })
  2. Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' )

Associating objects

Because Sequelize is doing a lot of magic, you have to call Sequelize.sync after setting the associations! Doing so will allow you the following:

  1. Project.hasMany(Task)
  2. Task.belongsTo(Project)
  3. Project.create()...
  4. Task.create()...
  5. Task.create()...
  6. // save them... and then:
  7. project.setTasks([task1, task2]).then(() => {
  8. // saved!
  9. })
  10. // ok, now they are saved... how do I get them later on?
  11. project.getTasks().then(associatedTasks => {
  12. // associatedTasks is an array of tasks
  13. })
  14. // You can also pass filters to the getter method.
  15. // They are equal to the options you can pass to a usual finder method.
  16. project.getTasks({ where: 'id > 10' }).then(tasks => {
  17. // tasks with an id greater than 10 :)
  18. })
  19. // You can also only retrieve certain fields of a associated object.
  20. project.getTasks({attributes: ['title']}).then(tasks => {
  21. // retrieve tasks with the attributes "title" and "id"
  22. })

To remove created associations you can just call the set method without a specific id:

  1. // remove the association with task1
  2. project.setTasks([task2]).then(associatedTasks => {
  3. // you will get task2 only
  4. })
  5. // remove 'em all
  6. project.setTasks([]).then(associatedTasks => {
  7. // you will get an empty array
  8. })
  9. // or remove 'em more directly
  10. project.removeTask(task1).then(() => {
  11. // it's gone
  12. })
  13. // and add 'em again
  14. project.addTask(task1).then(function() {
  15. // it's back again
  16. })

You can of course also do it vice versa:

  1. // project is associated with task1 and task2
  2. task2.setProject(null).then(function() {
  3. // and it's gone
  4. })

For hasOne/belongsTo it's basically the same:

  1. Task.hasOne(User, {as: "Author"})
  2. Task.setAuthor(anAuthor)

Adding associations to a relation with a custom join table can be done in two ways (continuing with the associations defined in the previous chapter):

  1. // Either by adding a property with the name of the join table model to the object, before creating the association
  2. project.UserProjects = {
  3. status: 'active'
  4. }
  5. u.addProject(project)
  6. // Or by providing a second options.through argument when adding the association, containing the data that should go in the join table
  7. u.addProject(project, { through: { status: 'active' }})
  8. // When associating multiple objects, you can combine the two options above. In this case the second argument
  9. // will be treated as a defaults object, that will be used if no data is provided
  10. project1.UserProjects = {
  11. status: 'inactive'
  12. }
  13. u.setProjects([project1, project2], { through: { status: 'active' }})
  14. // The code above will record inactive for project one, and active for project two in the join table

When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance:

  1. u.getProjects().then(projects => {
  2. const project = projects[0]
  3. if (project.UserProjects.status === 'active') {
  4. // .. do magic
  5. // since this is a real DAO instance, you can save it directly after you are done doing magic
  6. return project.UserProjects.save()
  7. }
  8. })

If you only need some of the attributes from the join table, you can provide an array with the attributes you want:

  1. // This will select only name from the Projects table, and only status from the UserProjects table
  2. user.getProjects({ attributes: ['name'], joinTableAttributes: ['status']})

Check associations

You can also check if an object is already associated with another one (N:M only). Here is how you'd do it:

  1. // check if an object is one of associated ones:
  2. Project.create({ /* */ }).then(project => {
  3. return User.create({ /* */ }).then(user => {
  4. return project.hasUser(user).then(result => {
  5. // result would be false
  6. return project.addUser(user).then(() => {
  7. return project.hasUser(user).then(result => {
  8. // result would be true
  9. })
  10. })
  11. })
  12. })
  13. })
  14. // check if all associated objects are as expected:
  15. // let's assume we have already a project and two users
  16. project.setUsers([user1, user2]).then(() => {
  17. return project.hasUsers([user1]);
  18. }).then(result => {
  19. // result would be true
  20. return project.hasUsers([user1, user2]);
  21. }).then(result => {
  22. // result would be true
  23. })

Foreign Keys

When you create associations between your models in sequelize, foreign key references with constraints will automatically be created. The setup below:

  1. const Task = this.sequelize.define('task', { title: Sequelize.STRING })
  2. const User = this.sequelize.define('user', { username: Sequelize.STRING })
  3. User.hasMany(Task)
  4. Task.belongsTo(User)

Will generate the following SQL:

  1. CREATE TABLE IF NOT EXISTS `User` (
  2. `id` INTEGER PRIMARY KEY,
  3. `username` VARCHAR(255)
  4. );
  5. CREATE TABLE IF NOT EXISTS `Task` (
  6. `id` INTEGER PRIMARY KEY,
  7. `title` VARCHAR(255),
  8. `user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
  9. );

The relation between task and user injects the user_id foreign key on tasks, and marks it as a reference to the User table. By default user_id will be set to NULL if the referenced user is deleted, and updated if the id of the user id updated. These options can be overridden by passing onUpdate and onDelete options to the association calls. The validation options are RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL.

For 1:1 and 1:m associations the default option is SET NULL for deletion, and CASCADE for updates. For n:m, the default for both is CASCADE. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.

Adding constraints between tables means that tables must be created in the database in a certain order, when using sequelize.sync. If Task has a reference to User, the User table must be created before the Task table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has a reference to its current version.

  1. const Document = this.sequelize.define('document', {
  2. author: Sequelize.STRING
  3. })
  4. const Version = this.sequelize.define('version', {
  5. timestamp: Sequelize.DATE
  6. })
  7. Document.hasMany(Version) // This adds document_id to version
  8. Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id'}) // This adds current_version_id to document

However, the code above will result in the following error: Cyclic dependency found. 'Document' is dependent of itself. Dependency Chain: Document -> Version => Document. In order to alleviate that, we can pass constraints: false to one of the associations:

  1. Document.hasMany(Version)
  2. Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id', constraints: false})

Which will allow us to sync the tables correctly:

  1. CREATE TABLE IF NOT EXISTS `Document` (
  2. `id` INTEGER PRIMARY KEY,
  3. `author` VARCHAR(255),
  4. `current_version_id` INTEGER
  5. );
  6. CREATE TABLE IF NOT EXISTS `Version` (
  7. `id` INTEGER PRIMARY KEY,
  8. `timestamp` DATETIME,
  9. `document_id` INTEGER REFERENCES `Document` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
  10. );

Enforcing a foreign key reference without constraints

Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.

  1. // Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series)
  2. const Series = sequelize.define('series', {
  3. title: DataTypes.STRING,
  4. sub_title: DataTypes.STRING,
  5. description: DataTypes.TEXT,
  6. // Set FK relationship (hasMany) with `Trainer`
  7. trainer_id: {
  8. type: DataTypes.INTEGER,
  9. references: {
  10. model: "trainer",
  11. key: "id"
  12. }
  13. }
  14. })
  15. const Trainer = sequelize.define('trainer', {
  16. first_name: DataTypes.STRING,
  17. last_name: DataTypes.STRING
  18. });
  19. // Video has a series_id=Series.id foreign reference key after we call Series.hasOne(Video)...
  20. const Video = sequelize.define('video', {
  21. title: DataTypes.STRING,
  22. sequence: DataTypes.INTEGER,
  23. description: DataTypes.TEXT,
  24. // set relationship (hasOne) with `Series`
  25. series_id: {
  26. type: DataTypes.INTEGER,
  27. references: {
  28. model: Series, // Can be both a string representing the table name, or a reference to the model
  29. key: "id"
  30. }
  31. }
  32. });
  33. Series.hasOne(Video);
  34. Trainer.hasMany(Series);

Creating with associations

An instance can be created with nested association in one step, provided all elements are new.

Creating elements of a "BelongsTo", "Has Many" or "HasOne" association

Consider the following models:

  1. const Product = this.sequelize.define('product', {
  2. title: Sequelize.STRING
  3. });
  4. const User = this.sequelize.define('user', {
  5. first_name: Sequelize.STRING,
  6. last_name: Sequelize.STRING
  7. });
  8. const Address = this.sequelize.define('address', {
  9. type: Sequelize.STRING,
  10. line_1: Sequelize.STRING,
  11. line_2: Sequelize.STRING,
  12. city: Sequelize.STRING,
  13. state: Sequelize.STRING,
  14. zip: Sequelize.STRING,
  15. });
  16. Product.User = Product.belongsTo(User);
  17. User.Addresses = User.hasMany(Address);
  18. // Also works for `hasOne`

A new Product, User, and one or more Address can be created in one step in the following way:

  1. return Product.create({
  2. title: 'Chair',
  3. user: {
  4. first_name: 'Mick',
  5. last_name: 'Broadstone',
  6. addresses: [{
  7. type: 'home',
  8. line_1: '100 Main St.',
  9. city: 'Austin',
  10. state: 'TX',
  11. zip: '78704'
  12. }]
  13. }
  14. }, {
  15. include: [{
  16. association: Product.User,
  17. include: [ User.Addresses ]
  18. }]
  19. });

Here, our user model is called user, with a lowercase u - This means that the property in the object should also be user. If the name given to sequelize.define was User, the key in the object should also be User. Likewise for addresses, except it's pluralized being a hasMany association.

Creating elements of a "BelongsTo" association with an alias

The previous example can be extended to support an association alias.

  1. const Creator = Product.belongsTo(User, {as: 'creator'});
  2. return Product.create({
  3. title: 'Chair',
  4. creator: {
  5. first_name: 'Matt',
  6. last_name: 'Hansen'
  7. }
  8. }, {
  9. include: [ Creator ]
  10. });

Creating elements of a "HasMany" or "BelongsToMany" association

Let's introduce the ability to associate a product with many tags. Setting up the models could look like:

  1. const Tag = this.sequelize.define('tag', {
  2. name: Sequelize.STRING
  3. });
  4. Product.hasMany(Tag);
  5. // Also works for `belongsToMany`.

Now we can create a product with multiple tags in the following way:

  1. Product.create({
  2. id: 1,
  3. title: 'Chair',
  4. tags: [
  5. { name: 'Alpha'},
  6. { name: 'Beta'}
  7. ]
  8. }, {
  9. include: [ Tag ]
  10. })

And, we can modify this example to support an alias as well:

  1. const Categories = Product.hasMany(Tag, {as: 'categories'});
  2. Product.create({
  3. id: 1,
  4. title: 'Chair',
  5. categories: [
  6. {id: 1, name: 'Alpha'},
  7. {id: 2, name: 'Beta'}
  8. ]
  9. }, {
  10. include: [{
  11. model: Categories,
  12. as: 'categories'
  13. }]
  14. })