顺序化-顺序和限制包括

时间:2019-11-25 13:29:54

标签: node.js sequelize.js

我有一个用户,问答模型,其中:

User.hasMany(Question, { as: 'questions', foreignKey: 'user_id' })
Question.belongsTo(User, { as: 'user', foreignKey: 'user_id' })

Question.hasMany(Answer, { as: 'answers', foreignKey: 'question_id' })
Answer.belongsTo(Question, { as: 'question', foreignKey: 'question_id' })

我想向用户查询所有问题,并且还希望包括问题和答案,但是我想将它们限制为5,并按created_at进行排序,因此最新的是第一位的。我应该如何构造查询?以下是我所拥有的:

const records = await User.findAll({
    include: [
      {
        model: Question,
        as: 'questions',
        include: [{ model: Answer, as: 'answers' }],
      },
    ],
    order: [
      [
        { model: Question, as: 'questions' },
        { model: Answer, as: 'answers' },
        'created_at',
        'desc',
      ],
    ],
  });

0 个答案:

没有答案