简体   繁体   中英

How do approach one to many association in sequelize?

I have a forumposts table with the following columns: id (primary key), categoryId, headline, content.

I have another table, forumcategories, with the following columns: id (primary key), name

The categoryid column in forumposts corresponds to the id column in forumcategories.

How do I associate the two tables?

You can do like this

 let ForumPost = sequelize.define('ForumPost', {/* ... */})
 let ForumCategory = sequelize.define('ForumCategory', {/* ... */})

 ForumCategory.hasMany(ForumPost, {as: 'forumposts'})

OR

ForumCategory.hasMany( ForumPost, { as: 'forumposts' } );
ForumPosts.hasOne( ForumCategory );

You may refer Sequelize Associations for further details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM