Hayden
Hayden

Reputation: 857

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?

Upvotes: 0

Views: 42

Answers (1)

Vipul Patil
Vipul Patil

Reputation: 1456

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.

Upvotes: 1

Related Questions