簡體   English   中英

使用Sequelize如何指定要排序/限制的字段?

[英]Using Sequelize how can I specify which field to sort / limit by?

我的查詢是:

    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", )。 我怎樣才能做到這一點?

您是否嘗試定義自定義范圍 ,比如randomrandom排序問題,然后在查詢中使用該范圍,如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM