获取包含数组所有ids的数据

Get data that contains all the ids of the array

我正在尝试过滤歌曲,我有一组从客户端检索到的流派 ID,我这样做是为了从一个 ID 获取所有音频:

Audio.findAll({
  include: [{
    model: db.Genres,
    as: "genres",
    where: {
      id: {
        [Op.and]: [1]
      }
    },
  }]
})

但我需要从 genres/moods 的数组中获取包含所有 ID 的所有音频,还想按流派 ID 和情绪 ID 过滤音频,但我不知道如何制作,任何想法? (一首歌可以有很多genres/moods)

歌曲模型

const Audio =  sequelize.define('Audio', {
  id: {
    autoIncrement: true,
    type: DataTypes.INTEGER(30),
    allowNull: false,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
})
Audio.associate = function(models) {
  Audio.belongsToMany(models.Genres, {through: 'AudioGenres', foreignKey: 'id_audio', as: 'genres'})
  Audio.belongsToMany(models.Moods, {through: 'AudioMoods', foreignKey: 'id_audio', as: 'moods'})
}

AudioGenreModel

const AudioGenres =  sequelize.define('AudioGenres', {
  id_audio: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    references: {
      model: 'Audio',
      key: 'id'
    }
  },
  id_genre: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    references: {
      model: 'Genres',
      key: 'id'
    }
})
AudioGenres.associate = function(models) {
  AudioGenres.belongsTo(models.Audio, {foreignKey: 'id_audio'})
  AudioGenres.belongsTo(models.Genres, {foreignKey: 'id_genre'})
};

AudioMoodModel

const AudioMoods =  sequelize.define('AudioMoods', {
  id_audio: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    references: {
      model: 'Audio',
      key: 'id'
    }
  },
  id_mood: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    references: {
      model: 'Mods',
      key: 'id'
    }
})
AudioMoods.associate = function(models) {
  AudioMoods.belongsTo(models.Audio, {foreignKey: 'id_audio'})
  AudioMoods.belongsTo(models.Mods, {foreignKey: 'id_mood'})
};

情绪和流派模型

const Moods =  sequelize.define('Moods', {
  name: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
})
Moods.associate = function(models) {
  Moods.belongsToMany(models.Audio, {through: 'AudioMoods', foreignKey: 'id_mood', as: 'audios'})
}

const Genres =  sequelize.define('Genres', {
  name: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
})
Genres.associate = function(models) {
  Genres.belongsToMany(models.Audio, {through: 'AudioGenres', foreignKey: 'id_genre', as: 'audios'})
}

我想您应该在两个 include 选项中的 AND 运算符中添加所有条件,如下所示:

Audio.findAll({
  include: [{
    model: db.Genres,
    as: "genres",
    where: {
      [Op.and]: [{ id: 1}, { id: 3},{ id: 2}]
    },
  }, {
    model: db.Moods,
    as: "moods",
    where: {
      [Op.and]: [{ id: 4}, { id: 5},{ id: 6}]
    },
  }]
})