2016-11-22 92 views
1

我有以下结构:Sequelize许多一对多表具有相同的外键只选择一个值

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'}); 

我能创造数倍意见同一职位与用户。

但如果我有相同的岗位使用相同的用户不止一个注释,并尝试做选择它们:

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

它只是返回1条评论在后每个用户。我需要做些什么来选择它们?

方言:mysql的, Sequelize版本:〜3.27.0

回答

2

BelongsToMany有关联和相同的ID是Sequelize莫名其妙棘手。

正如您在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" 
     .. 

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

+0

当我尝试这样做时,它会在执行查询时引发错误:“未处理的拒绝类型错误:无法读取未定义的属性”getTableName“。 但它适用于创建新实例 –

+0

我的不好,这是一个语法错误,你解决方案为我工作。谢谢 –

相关问题