Tuesday 6 June 2017

Sequelize model one-to-many relationship bi-directionally

I'm using Sequelize to build a mobile social-networking application and I want to model a relationship between users and things that they post.

Let's say I have a model called User and a model called Post. Each post belongs to a particular User and each user has a list of Posts. I want to model the one-to-many relationship bi-directionally so that when I query my users, each will have an array of identifiers that link to Post objects.

I'm defining this relationship as:

Post.belongsTo(User);
User.hasMany(Post, { foreignKey: 'posts' })

This successfully adds a userId field to all my posts but my user queries come back without the added foreign key posts. Does anyone know why it's not getting added?



via barndog

No comments:

Post a Comment