Ask Your Question
0

How can I get Sequelize to return all associations when performing a search with a "where" clause?

asked 2023-06-11 11:48:08 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-11 12:10:01 +0000

bukephalos gravatar image

You can use the include option in Sequelize to specify which associations you want to include in the result when performing a search with a where clause.

Here is an example:

const User = db.define('user', {
  name: Sequelize.STRING,
})

const Post = db.define('post', {
  title: Sequelize.STRING,
  body: Sequelize.TEXT
})

const Comment = db.define('comment', {
  body: Sequelize.TEXT
})

// associations
User.hasMany(Post)
Post.belongsTo(User)
Post.hasMany(Comment)
Comment.belongsTo(Post)

// search with where clause and include associations
const posts = await Post.findAll({
  where: {
    id: 1
  },
  include: [
    {
      model: User,
      attributes: ['id', 'name']
    },
    {
      model: Comment,
      include: [
        {
          model: User,
          attributes: ['id', 'name']
        }
      ]
    }
  ]
})

In this example, we are searching for a post with id 1 and including the User and Comment associations with their respective attributes. The Comment association also includes the User association with their respective attributes.

This will return a result set that includes all the associated data for the post, the user who created it, and all the comments with their associating users.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-11 11:48:08 +0000

Seen: 14 times

Last updated: Jun 11 '23