序列化具有相同外键的多对多表只select一个值

我有以下结构:

var User = sequelize.define('user', { name: DataTypes.STRING }); var Post = sequelize.define('post', { text: DataTypes.STRING }); var PostComment = sequelize.define('postComment ', { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true }, comment: DataTypes.TEXT }); Post.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'}); User.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'}); 

我能够与用户创build多个评论到同一职位。

但是,如果我对同一用户的同一post有更多然后一个评论,并试图通过做select他们:

  Post.findAll({ include: [{model: models.User, as: 'postUserComment', attributes:['name'], through: {attributes: ['comment']}}, limit: 10, offset: 0, order: "id DESC" ... 

它只是为每个用户在post中返回1条评论。 我需要做些什么来select他们呢?

方言:mysql,Sequelize版本:〜3.27.0

在Sequelize中,与BelongsToMany和相同的id有关联是非常棘手的。

正如你已经注意到GitHub#6906和其他相关的问题那样,最好的办法就是用不同的关系缓解它。

例如,你可以添加:

 Post.hasMany( models.PostComment, { foreignKey: 'idPost' } ); 

然后到你的查询

 Post.findAll({ include: [ {model: models.User, as: 'postUserComment', attributes:['name'], through: {attributes: ['comment']}}, {model : models.PostComment} ], limit: 10, offset: 0, order: "id DESC" .. 

这不会改变你的数据库结构,并会有你想要的效果。