2014-07-02 19 views
1

我有以下几点:

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); 

过滤器的工作原理。但是,显然,用户将看到所有用户记录。

更新: 如果不是使用条件PARAMS性能我用compare()方法,像这样:

$criteria->compare('entity_id',$entity->id); 

它的工作原理。

它为什么会与比较,而不是条件和参数?

回答

1

当您使用此

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); 
     } 

会发生什么是条件属性重置(由于新的分配),你刚才所用的比较功能追加相比,条件见http://www.yiiframework.com/doc/api/1.1/CDbCriteria#compare-detail信息关于如何工作,因此,当你做一个新的任务时,它会清除所有现有的条件。

所以要么你可以使用新标准的物体,像下面

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_AUTHOR

相关问题