[英]how to select record from table where record have the most similar attribute from another table
[英]Yii select first record from table where it does not have a record in a related table
我有一個帶有兩個表的MySQL數據庫:
quiz_questions有2列:
quiz_results
我想得到下一個沒有任何結果的問題。 換句話說,獲得在結果表中找不到ID的問題
我發現原始SQL是這樣的:
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;
如何使用模型達到相同目的?
謝謝
我沒有嘗試過,但是它可能會給您一些起點。
在問題模型中
public function relations()
{
return array(
'results' => array(self::HAS_MANY, 'Result', 'question_id'),
);
}
在結果模型中
public function relations()
{
return array(
'question' => array(self::BELONGS_TO, 'Question', 'question_id'),
);
}
向問題添加靜態函數
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);
}
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.