當然這是可能的。 您可以創建範圍,如:
public function scopes()
{
return array(
'enabled' => array(
'condition' => 'status=0',
),
'banned' => array(
'condition' => 'status=1',
),
);
}
然後在查詢中你會碰到這樣的:
$activeUsers = User::model()->enabled()->findAll();
$bannedUsers = User::model()->banned()->findAll();
此外,您還可以有一個名爲範圍:
public function statusIs($status)
{
// you can accept a status string here and translate it in an integer, your choice.
return $this->getDbCriteria()->mergeWith(array(
'condition' => 'status = '.(int)$status
));
}
並使用它在您的查詢如:
User::model()->statusIs(0)->findAll();// get all enabled
此外,使用範圍就可以查詢你的相關模型爲好,這樣的:
Posts::model()->with('users:enabled')->findAll();
應該工作了。
只需看看http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes並查看更多。
LE:
public function getStatuses()
{
return array(
'0' => Yii::t("status", 'Enabled'),
'1' => Yii::t("status", 'Banned'),
'2' => Yii::t("status", 'Disabled'),
);
}
public function getStatusesDropDown(array $htmlOpts = array())
{
return CHtml::activeDropDownList($this, 'status', $this->getStatuses(),$htmlOpts);
}
現在,你有下拉的代碼,在你的CActiveForm,或者告訴你這個狀態的任何其他形式的下拉菜單,如:
echo $model->getStatusesDropDown();
當你選擇一個狀態從下拉菜單中提交表單,將會提交名爲YourModel[status]
的輸入。這將有0或1或2,接下來的值,在你search()
方法,你必須:
public function search()
{
$criteria = new CDbCriteria;
[...]
if ($this->status !== null && (int)$this->status >= 0) {
$criteria->compare('status', (int)$this->status);
}
[...]
}
而這幾乎是它。
謝謝你的迴應。但是現在我想在我的模型的search()函數中使用這個研究,使用$ criteria-> compare('status',this-> status)。你能告訴我你是怎麼做到的嗎? – Florent
定義了一個下拉列表,其值爲0,1,2以及您的狀態的名稱,然後當您的search()方法檢索值時,您可以直接比較它們,如上所述 – Twisted1919
對不起,但可以你給我一個代碼示例? – Florent