【问题标题】:Using Sequelize how can I specify which field to sort / limit by?使用 Sequelize 如何指定要排序/限制的字段?
【发布时间】:2016-06-15 16:34:06
【问题描述】:

我的查询是:

    db.Question.findAll
      where:
        id:
          $notIn: if questionIds.length > 0 then questionIds else [-1]
        TopicId: topicCount.id
        PassageId: null
        status: 'active'
        level:
          $lte: startLevel
          $gte: endLevel
      include: [
        model: db.Answer
      ]
      order: [db.Sequelize.fn 'RANDOM']
      limit: questionSections[sectionIndex].goal * 2

这会生成以下查询:

SELECT "Question".*, 
       "answers"."id"         AS "Answers.id", 
       "answers"."answertext" AS "Answers.answerText", 
       "answers"."iscorrect"  AS "Answers.isCorrect", 
       "answers"."createdat"  AS "Answers.createdAt", 
       "answers"."updatedat"  AS "Answers.updatedAt", 
       "answers"."questionid" AS "Answers.QuestionId" 
FROM   (SELECT "Question"."id", 
               "Question"."status", 
               "Question"."questiontext", 
               "Question"."level", 
               "Question"."originalid", 
               "Question"."createdbyuserid", 
               "Question"."editedbyuserid", 
               "Question"."createdat", 
               "Question"."updatedat", 
               "Question"."instructionid", 
               "Question"."topicid", 
               "Question"."subjectid", 
               "Question"."passageid" 
        FROM   "questions" AS "Question" 
        WHERE  "Question"."id" NOT IN ( -1 ) 
               AND "Question"."topicid" = '79' 
               AND "Question"."passageid" IS NULL 
               AND "Question"."status" = 'active' 
               AND ( "Question"."level" <= 95 
                     AND "Question"."level" >= 65 ) 
        LIMIT  300) AS "Question" 
       LEFT OUTER JOIN "answers" AS "Answers" 
                    ON "Question"."id" = "answers"."questionid" 
ORDER  BY Random(); 

这一切都很好,除了我希望 ORDER BY 应用于内部查询 (SELECT "Question"."id", "Question"."status",)。我怎样才能做到这一点?

【问题讨论】:

  • ORDER BY添加到内部查询的目的是为了让LIMIT 300导致300个随机元组被选为左连接的候选者,对吧?
  • 对——这就是我想要的

标签: javascript node.js sequelize.js


【解决方案1】:

您是否尝试过定义自定义scope,比如random,随机排序问题,然后在查询中使用该范围,例如:

db.Question.scope('random').findAll({
  where:{
    ..........
  },
  include: [{
    model: db.Answer
  }],
  //order: [db.Sequelize.fn 'RANDOM'] <<<<<<< moved to custom scope
  limit: questionSections[sectionIndex].goal * 2
 })

【讨论】:

    猜你喜欢
    • 2015-02-05
    • 1970-01-01
    • 2014-04-27
    • 2011-12-23
    • 2019-09-02
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多