Sequelize in the association use of the explanation, Nodejs

Source: Internet
Author: User
Tags findone

Note: This article uses Sequelize 1.7.0. Examples have been tested and can be used with confidence.

It is easy to use sequelize to organize the Nodejs program back-end architecture in the MVC pattern. This article, in the author's opinion, one of the more useful and somewhat difficult association to share.

Typically, there are three relationships between models,1:1,1:n,n:m. The following examples are broken down.

1:1. If there is a user and userinfo two models, respectively, corresponding users, as well as the user's data. At this point, each user should have and only one user profile, thus, the user's relationship with Uerinfo should be 1:1. In sequelize, use Hasone and Belongsto to describe. In the actual model

 1  //  2  Associate: function   (models) { 3   User. HasOne (models. UserInfo);  4  }   // in UserInfo model  6  Associate: function   (models) { 7   Userinfo.belongsto (models. User);  8 } 

In the above code, it is said that a user has a userinfo, a userinfo in turn belongs to a user. The relationship between the two sides is established. After running the code, Sequelize automatically adds a foreign key userid to the UserInfo. When searching for userinfo, you can use the following two ways:

1 models. User.findone ({2 where:{Id:userid},3Include: {model:models. UserInfo, as: ' Info '}4}). Then (function(user) {5          /*{6 name: ' xxx ',7 UserInfo: {8 email: ' xxx '9             }Ten  One         }*/ A     }); - models. User.findone ({ - Where:{id:id} the}). Then (function(user) { -User.getuserinfo (). Then (function(info) { -         /*{ - email: ' xxx ', + sex: ' Male ', - Profile : ' Usl:xxx ' +         } A         */ at     }) -});

1:n. If a person wants to post a blog, then a person user should send a lot of blog post article, so the relationship between user and article can be appropriately expressed as 1:n. The description of analogy 1:1 is represented by the use of Hasmany and Belongsto in Sequelize. The code is similar to 1:1 and is no longer verbose.

N:m. This is more complex than the first two, and explaining this is actually the main purpose of this blog post. For a more comprehensive and in-depth explanation, a particularly complex example is given. The two models were user users and article topic. The relationship between them is: (1:N) The user wrote a lot of articles, each article only one author; (n:m) If there is a collection function, the user will collect some articles, each article will also be collected by many people. That would have been possible, but in order to add complexity, a n:m relationship was introduced, and the article was evaluated by the user. Sequelize is the use of belongstomany to represent n:m relationships. In this many-to-many relationship, especially in this case, there are a number of many-to-many relationships, for a clearer description, usually introduce another relationship table. For details, please refer to the following code:

1 /*In User model*/2Associatefunction(models) {3User.hasmany (models. Topic, {as: ' Authortopics ', ForeignKey: ' Authorid '});4User.belongstomany (models. Topic, {as: ' Watchedtopics ', through: ' Userwatchedtopic '});5User.belongstomany (models. Topic, {as: ' Commentedtopics ', Through:models. Usercommenttopic});6 }7 /*In Topic*/8Associatefunction(models) {9Topic.belongsto (models. User, {as: ' Author ', ForeignKey: ' Authorid '});TenTopic.belongstomany (models. User, {as: ' watchors ', through: ' Userwatchedtopic '}); OneTopic.belongstomany (models. User, {as: ' commenters ', Through:models. Usercommenttopic}); A}


These two kinds of n:m relationship respectively used two tables userwatchedtopic, Usercommenttopic to describe. Userwatchedtopic uses strings directly, and is suitable for simple many-to-many relationships. When we want to record some of the two things in this n:m relationship, for example, if you want to merge the first type of author into a n:m relationship, you can add the Isauthor field to the Usercommenttopic to mark it. Of course, I think this will complicate the relationship and damage the brain cells.

If we are going to get followers of an article, we can do this:

1 models. Topic.findone ({2      where: {id:id}3 }). Then (function(Topic) { 4      Topic.getwatchors (). Then (function(watchers) {5/             *6  7 */8})           9 })            

That ' s it.

If you have any questions, please feel free to discuss them. [Email protected]

Sequelize in the association use of the explanation, Nodejs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.