当然这是可能的。 您可以创建范围,如:
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