猿问

在 Sequelize 中切换关联(同时进行一对多和多对多)

我有桌子User,,Assignment。可以创建很多个s,这些s只会分配给他,即association。但是很多s可以添加很多s到自己的收藏夹中,即通过表格关联。FavoriteAssignmentUserAssignmentone to manyUserAssignmentmany to manyFavoriteAssignment


我如何才能包含User的创建的作业或他最喜欢的作业?我的意思是,在使用sequelize进行包含时,我应该如何在关联之间切换?


用户协会:


  class User extends Model {

    static associate(models) {

      User.hasMany(models.Assignment, { foreignKey: 'authorTelegramId'});

      User.belongsToMany(models.Assignment, { through: 'FavoriteAssignments', foreignKey: 'telegramId'});

    }

  };

作业关联:


  class Assignment extends Model {

    static associate(models) {

      Assignment.belongsTo(models.User, {foreignKey: 'authorTelegramId'});

      Assignment.belongsToMany(models.User, {through: 'FavoriteAssignments', foreignKey: 'assignmentId'});

    }

  };

FavouriteAssignment 的关联:


  class FavoriteAssignment extends Model {

    static associate(models) {

      FavoriteAssignment.belongsTo(models.User, {foreignKey: 'telegramId'});

      FavoriteAssignment.belongsTo(models.Assignment, {foreignKey: 'assignmentId'});

    }

  };

我提出这个问题是因为当我这样做时:


const result = await db.User.findAll({

    include: [{

        model: db.Assignment

    }]

});

它获取所有User最喜欢的作业,如belongsToMany最后定义的那样!如果我注释User.belongsToMany(models.Assignment, { through: 'FavoriteAssignments', foreignKey: 'telegramId'});行,那么它将获取所有User创建的作业(one to many关联)。


如果我有多个关联,如何选择要使用的关联?


慕无忌1623718
浏览 121回答 1
1回答

青春有我

基本上我必须这样命名关联:  User.hasMany(models.Assignment, { foreignKey: 'authorTelegramId', as: 'assignments'});  User.belongsToMany(models.Assignment, { through: 'FavoriteAssignments', foreignKey: 'telegramId', as: 'favoriteAssignments'});然后调用它:const result = await db.User.findAll({    include: ['assignments']});const result1 = await db.User.findAll({    include: ['favoriteAssignments']});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答