Tutorial on Association use in Nodejs sequelize framework

Source: Internet
Author: User
Tags findone

The sequelize can be used to organize the NODEJS program back-end architecture in a more convenient way according to the MVC pattern. This article, in the author's opinion, which is more useful and slightly difficult association to share.

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

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

In User model
Associate:function (models) {
User. Hasone (Models. UserInfo);
}
In UserInfo model
associate:function (models) {
Userinfo.belongsto (models. User);
}


Above this code, it is said that a user has a userinfo, a userinfo in turn belong to a user. Thus the relationship between the two sides is established. After the code is run, Sequelize automatically adds a foreign key userid to the userinfo. If you need to get userinfo when searching, you can use the following two ways:

Models. User.findone ({        where:{ id: userid },          include: {model: models. userinfo, as:  ' Info '}    &nbsp. Then (function (user) {          /*{            name:  ' xxx ',             userinfo: {                 email:  ' xxx '              }        
 }*/    }); Models. User.findone ({    where:{id: id}}). Then (function (user) {     User.getuserinfo (). Then (function (info) {        /*{   &NBsp;        email: ' xxx ',              sex:  ' Male ',              profile:  ' usl:xxx '         }          */   &nbsp});


1:n. If a person wants to send a blog, then a person user should send a lot of blog posts article, so that the relationship between user and article can be properly expressed as 1:n. Analogy 1:1 describes the way in which Sequelize is expressed using Hasmany and Belongsto. Code is the same as 1:1, no longer?? Long Br/>
N:m. This is more complicated than the first two, and explaining this is actually the main purpose of this blog post. In order to give a more thorough explanation, a very complicated example is given in particular. The two models are user users and article topic, respectively. 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, users will collect some articles, each article will be a lot of people's collection. Originally this can be, but in order to increase the complexity, specifically to introduce a n:m relationship, the article was evaluated by the user. Sequelize is the use of Belongstomany to express the n:m relationship. In this many-to-many relationship, especially in this case, there are many many-to-many relationships, and for a clearer description, another relational table is usually introduced. Refer to the following code specifically:

/*in user model*/associate: function (models)  {          user.hasmany (models.
topic, {as:  ' authortopics ', foreignkey:  ' Authorid '});    user.belongstomany (models.
topic, {as:  ' watchedtopics ', through:  ' userwatchedtopic '});    user.belongstomany (models. topic, {as:  ' Commentedtopics ',  through: models.
Usercommenttopic}); }/*in topic*/Associate: function (models)  {          Topic.belongsto (models.
user, {as:  ' Author ', foreignkey:  ' Authorid '});    topic.belongstomany (models.
user, {as:  ' watchors ', through:  ' userwatchedtopic '});    topic.belongstomany (models. user, {as:  ' commenters ',  through: models.
Usercommenttopic}); }



These two kinds of n:m relations are 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 second-order information in this n:m relationship, for example, if you currently want to merge the first one into the 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 brain cells.

If we want to get a focus on an article, you can do this:

Models. Topic.findone ({
where: {id:id}
}). Then (function (Topic) {
topic.getwatchors (). Then (function (Watchers ) {/
*
[{Watcher1}{watcher2}{watcher3}]/}
)




Node.js sequelize ORM Framework Multi-Table Association

There must be a relational mapping beyond the basic ORM mapping of the SQL database, Sequelize allows you to implement the most complex mappings with minimal code

Like what:
An article model and an article classification model relationship description.
Article.js article model

Var article = sequelize.define ("info", {    id: {type:  SEQUELIZE.UUIDV4, PRIMARYKEY: TRUE, DEFAULTVALUE: SEQUELIZE.UUIDV4},      category_id: {type:sequelize.string (+), allownull:false},     title:{type:
Sequelize.string (MB), allownull:false},     content:{type:sequelize.text,allownull:false},     imgurl:{type:sequelize.string (MB)},     remark:{type: Sequelize.string (+)},     ispublished:{type:sequelize.boolean,allownull:false},      creator_id:{type:sequelize.string (+), allownull:false},     createtime:{ Type:sequelize.date,defaultvalue:sequelize.now},     publishtime:{type:sequelize.date, DefaultValue:Sequelize.now},     publisher_id:{type:sequelize.string (+), Allownull:false}})
; Article.belongsto (category,{as: ' Category '), ForeignKey: ' category_id '});
Article.belongsto (staff,{as: ' Creator ', ForeignKey: ' creator_id '});
Article.belongsto (staff,{as: ' Publisher ', ForeignKey: ' publisher_id '});
Category.hasmany (article,{as: ' articles ', ForeignKey: ' category_id '});
Category.belongsto (staff,{as: ' Creator ', ForeignKey: ' creator_id '});
Category.belongsto (staff,{as: ' Publisher ', ForeignKey: ' publisher_id '}); module.exports = article;


Category

Var category = sequelize.define ("Category", {    id: {type:  SEQUELIZE.UUIDV4, PRIMARYKEY: TRUE, DEFAULTVALUE: SEQUELIZE.UUIDV4},      name: {type:sequelize.string (M), Allownull:false},     bigimgurl:{type: Sequelize.string (+)},     smallimgurl:{type:sequelize.string},      platecode:{type:sequelize.integer},     remark:{type:sequelize.string},      ispublished:{type:sequelize.boolean,allownull:false},     creator_id:{ Type:Sequelize.STRING (), allownull:false},     createtime:{type:sequelize.date, DefaultValue:Sequelize.now},     publishtime:{type:sequelize.date,defaultvalue:
Sequelize.now},     publisher_id:{type:sequelize.string (+), Allownull:false}}); module.exports = category;


Article.belongsto (category,{as: ' Category ', ForeignKey: ' category_id '}), which means that the article belongs to a category, that is, a one-to-one relationship. Use ' ForeignKey ' to identify foreign keys.
Category.hasmany (article,{as: ' articles ', ForeignKey: ' category_id '}); There are multiple articles under one category (of course you can also Article ' inside uses Belongstomany to indicate that the most recent version of the Sequelize many-to-many relationship is either Hasmany or Belongstomany to indicate that Sequelize will throw a red warning. Recommended two-way use of ' belongstomany ' can be.

The relationship above describes why I have unloaded article.js inside? is because the requere load sequence reason, if separately writes, after adds in the model will not initialize completes! So either write all of the model to a file (this method is obviously unacceptable), so it throws the relationship description all into the model that the individual thinks is most commonly used in the relationship.

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.