简体   繁体   中英

Yii select first record from table where it does not have a record in a related table

I have a MySQL database with two tables:

quiz_questions has 2 columns:

  • question_id (pk)
  • question

quiz_results

  • user_id (fk to user)
  • question_id (fk to question)
  • answer_id (fk to answer)

I would like to get the next question that does not have any results associated with it. In other words, get the question where the ID is not found in the results table

I figured out the raw SQL is this:

SELECT 
    qq.question_id, qq.question
FROM
    quiz_questions qq
LEFT JOIN 
    quiz_results qr
ON 
    qq.question_id = qr.question_id
WHERE
    isNull(qr.user_id)
ORDER BY question_id ASC
LIMIT 1;

How can I achieve the same using models?

Thanks

I haven't tried this but it might give you somewhere to start.

in the question model

    public function relations()
{
    return array(
        'results' => array(self::HAS_MANY, 'Result', 'question_id'),
    );
}

in the result model

    public function relations()
{
    return array(
        'question' => array(self::BELONGS_TO, 'Question', 'question_id'),
    );
}

Add a static function to question

public static function getUnansweredQuestion() {
    $criteria = new CDBCriteria();
    $criteria->with =
        array('result'=>array(
             'select'=>false,
             'together'=>true,  // Do the join but discard the result values
        );
    );
    $criteria->addCondition('t.question_id NOT IN 
        (SELECT question_id FROM quiz_results WHERE user_id = '.
        User::model()->findByAttributes(
            array('username'=>Yii::app()->user->name))->id.')');
    $criteria->limit = 1;
    $criteria->order = 't.id ASC';

    return Question::model()->find($criteria);
}

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM