【问题标题】:Sequelize Many-to-many table with identical foreign key is selecting just one valueSequelize 具有相同外键的多对多表只选择一个值
【发布时间】:2016-11-23 00:29:03
【问题描述】:

我有以下结构:

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

我可以为同一个用户创建多个 cmets。

但如果我对同一个用户的同一篇文章有​​多个评论,并尝试通过以下方式选择它们:

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

它只为帖子中的每个用户返回 1 条评论。我该怎么做才能全部选中?

方言:mysql, 续集版本:~3.27.0

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    在 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"
          ..
    

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

    【讨论】:

    • 当我尝试这样做时,它会在我执行查询时引发错误:“未处理的拒绝类型错误:无法读取未定义的属性 'getTableName'”。但它适用于创建新实例
    • 我的错,这是一个语法错误,你的解决方案对我有用。谢谢
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2023-03-24
    • 2022-08-17
    • 2023-03-31
    • 2020-11-26
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多