Sequelize - 未列出指定的相关对象时过滤父级

时间:2017-09-16 14:20:48

标签: sequelize.js

大家好,并提前感谢您的回复,

我与Sequelize有以下关联:

const ForumUser = require('./models').ForumUser;
const UserTopics = require('./models').UserTopics;
const Topic = require('./models').Topic;

ForumUser.belongsToMany(Topic, {
  through: UserTopics,
  foreignKey: 'user_id'
});

Topic.belongsToMany(ForumUser, {
  as: 'ForumUsers',
  through: UserTopics,
  foreignKey: 'topic_id'
});

我想在没有主持人回应的情况下检索主题(用户排名为7,8,23)。我可以在主持人做出回应但不反过来时过滤父母。

我试过这个:

Topic.findAll({
    attributes: ['id', 'subject', 'last_post_time'],
    where: {
      locked: { $ne: '1' },
      hold: 0
    },
    include: [
      {
        attributes: ['userid'],
        model: ForumUser,
        as: 'ForumUsers',
        include: {
          attributes: ['username'],
          model: User
        },
        where: {
          rank: {
            $notIn: [7, 8, 23]
          }
        }
      }
    ],
    order: [['last_post_time', 'DESC']],
    limit: 10
});

问题在于我还检索了包含来自非主持人的至少一个答案的所有主题。

有没有办法过滤不包含指定关系对象的父母?

1 个答案:

答案 0 :(得分:0)

最后,我解决了我的问题:

Topic.findAll({
    attributes: ['id', 'subject', 'last_post_time'],
    where: {
      locked: { $ne: '1' },
      hold: 0,
      '$ForumUsers.rank$': null
    },
    include: [
      {
        attributes: ['userid'],
        model: ForumUser,
        as: 'ForumUsers',
        include: {
          attributes: ['username'],
          model: User
        },
        where: {
          rank: {
            $in: [7, 8, 23]
          }
        },
        required: false
      }
    ],
    order: [['last_post_time', 'DESC']],
    limit: 10,
    subQuery: false
  }
相关问题