Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize include objects with scope 1:m constraint = false

I want to use same table Photo for other tables. I read Sequelize doc here they use scope and set constraint = false like this

const Comment = this.sequelize.define('comment', {
  title: Sequelize.STRING,
  commentable: Sequelize.STRING,
  commentable_id: Sequelize.INTEGER
});

Comment.prototype.getItem = function(options) {
  return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options);
};

Post.hasMany(this.Comment, {
  foreignKey: 'commentable_id',
  constraints: false,
  scope: {
    commentable: 'post'
  }
});
Comment.belongsTo(this.Post, {
  foreignKey: 'commentable_id',
  constraints: false,
  as: 'post'
});

my question is: HOW I can query list of Post that include list comments for each post (with limit if it's avaiable). Thank you.

like image 429
Robert Pham Avatar asked Aug 22 '26 20:08

Robert Pham


1 Answers

HOW I can query list of Post that include list comments for each post

Here, try this

Post
  .find({
    where: { /* include where condition if you have or remove this */ },
    include: [{
      model: Comment,
      as: 'comments',
    }],
  })
  .then(function(result) {
    // check result.dataValues. it should contain `comments` array
  });

The limit is not yet available i suppose. check this for updates https://github.com/sequelize/sequelize/issues/1897

like image 170
Theo Avatar answered Aug 24 '26 09:08

Theo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!