2016-03-02 5 views
5

La mia domanda è:Utilizzo di Sequenza come è possibile specificare il campo da ordinare/limitare?

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 

E che genera la seguente query:

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(); 

Questo è tutto bene, tranne che voglio che il ORDER BY da applicare alla query interna (SELECT "Question"."id", "Question"."status",). Come posso raggiungere questo obiettivo?

+0

Lo scopo di aggiungere 'ORDINE BY' alla query interna è così che il 'LIMIT 300' causa la selezione di 300 tuple casuali come candidati per il join sinistro, giusto? –

+0

Giusto: questo è quello che voglio – Shamoon

risposta

2

Hai provato la definizione personalizzata scope, dicono random, che ordina le domande in modo casuale e quindi utilizzando tale ambito nella query come:

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