Yii 如果我们使用`$criteria->;条件`和/或`$criteria->;参数`?
我有以下资料:Yii 如果我们使用`$criteria->;条件`和/或`$criteria->;参数`?,yii,Yii,我有以下资料: public function search() { $criteria = new CDbCriteria(); $criteria->compare('id',$this->id); $criteria->compare('entity_id',$this->entity_id); $criteria->compare('name',$this->name,true);
public function search() {
$criteria = new CDbCriteria();
$criteria->compare('id',$this->id);
$criteria->compare('entity_id',$this->entity_id);
$criteria->compare('name',$this->name,true);
(etc...)
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
当我应用此项时:
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
用户只能在CGridView上查看自己的记录。美好的
但是,由于某些原因,过滤器不起作用
如果我评论这些行:
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
过滤器工作正常。但是,显然,用户将看到所有用户的记录
更新:
如果我没有使用条件和参数属性,而是使用compare()
方法,如下所示:
$criteria->compare('entity_id',$entity->id);
它起作用了
为什么它与compare一起工作,而不与condition和params一起工作?使用此选项时
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
发生的情况是条件属性被重置(由于新的赋值),您先前使用的比较函数将比较附加到条件中。有关如何工作的信息,请参阅。因此,当您执行新的赋值时,它将清除所有现有条件
因此,您可以使用如下所示的新标准对象
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria2= new CDbCriteria();
$criteria2->condition = 'entity_id=:entity_id';
$criteria2->params = array(':entity_id'=>$entity->id);
$criteria->mergeWith($criteria2);
}
或者,您可以在比较语句之前移动SiteUser::ROLE\u AUTHOR
的逻辑