【问题标题】:Many-to-Many association throws "A is not associated to B" error多对多关联抛出“A 未关联到 B”错误
【发布时间】:2020-09-05 19:04:57
【问题描述】:

我正在尝试制作一个 API,其中:

  • 每个用户可以拥有多首歌曲。
  • 并且每首歌曲都可以有很多喜欢(用户)

我是 Sequelize 的新手,所以我正在努力解决这个问题。 (请记住,一对多关联有效,但多对多无效)

这是我的模型和迁移:

模型/user.js:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
  }, {});
  User.associate = function(models) {
    User.hasMany(models.Song, {
      foreignKey: 'userId',
      as: 'songs',
      onDelete: 'CASCADE'
    });
    User.belongsToMany(models.Song, {
      through: 'UserSongLike',
      foreignKey: 'userId',
      otherKey: 'songId',
      as: 'songsList',
      onDelete: 'CASCADE'
    });
  };
  return User;
};

模型/song.js:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Song = sequelize.define('Song', {
    userId: DataTypes.INTEGER,
    title: DataTypes.STRING
  }, {});
  Song.associate = function(models) {
    Song.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'songBy',
      onDelete: 'CASCADE'
    });
    Song.belongsToMany(models.User, {
      through: 'UserSongLikes',
      foreignKey: 'songId',
      otherKey: 'userId',
      as: 'likedBy',
      onDelete: 'CASCADE'
    });
  };
  return Song;
};

模型/usersonglike.js:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const UserSongLike = sequelize.define('UserSongLike', {
    userId: DataTypes.INTEGER,
    songId: DataTypes.INTEGER
  }, {});
  UserSongLike.associate = function(models) {
    // associations can be defined here
  };
  return UserSongLike;
};

您可以在此处找到迁移:https://gist.github.com/ExillustX/199b068912aae6368176718df13183e6

现在当我尝试查询以下代码时:

try {
  const query = await models.UserSongLike.findAll({
    include: [
      {
        model: models.User,
        as: "users",
        through: {
          model: models.UserSongLike,
          as: 'UserSongLikes',
        }
      }
    ]
  });
  console.log(query)
} catch (err) {
  console.log(er)
}

我收到一个错误:EagerLoadingError [SequelizeEagerLoadingError]: User is not associated to UserSongLike!

我不确定为什么会发生这种情况,可能是因为我没有在迁移(或模型)中添加表引用吗?

感谢任何帮助!

【问题讨论】:

    标签: node.js database postgresql sequelize.js


    【解决方案1】:

    需要关联UserSongUserSongLike是中间表,这里不需要声明,关系由sequelize自动创建。

    你可以试试这样的:

    try {
      const query = await models.User.findAll({
        include: [
          {
            model: models.Song,
          }
        ]
      });
      console.log(query)
    } catch (err) {
      console.log(er)
    }
    

    【讨论】:

    • 非常感谢,尽管我在看到您的回答之前就已经解决了这个问题!还是接受了!
    • 我有一个问题,我需要向模型和迁移添加属性选项(如引用、allownull、验证等)吗?或者将它们添加到模型中就足够了吗?抱歉,我不习惯迁移!
    • 最好通知attributes options。如果您有包含很多列的表,那么描述您想要哪些列会使事情变得更快,因为 sequelize 仅解析您选择的列。另外,如果您只想关联表格而不需要任何列,您可以告知:attributes: [] 以避免在表格上出现SELECT *
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多