1

我正在编写多用户应用程序。在每个模型中,我都有一个字段 user_id,每个用户登录,我都可以获得他的 id: Yii::app()->user->id

我不想在每个动作查找/更新/插入条件中重复它,所以如何在模型 user_id 中设置它?

4

2 回答 2

1

使用 CActiveRecordBehavior。这样,您可以为所有模型挂钩 beforeFind/afterFind 和 beforeSave/afterSave 事件。真的很不错

于 2013-02-06T05:43:19.197 回答
0

您必须创建父类并继承它

abstract class UserAccess extends CActiveRecord {

    public function getUserAccessCondition($condition, array $params)
    {
        if ($condition instanceof CDbCriteria) {
            $condition->compare('user_id', Yii::app()->user->id);
        } else {
            if(!is_array($condition)) {
                $condition['condition'] = $condition;
                $condition['params'] = $params;
            }
            if (trim($condition['condition']) == '') $condition['condition'] = 'user_id=:user_id';
            else $condition['condition'] .= ' and user_id=:user_id';
            $params[':user_id'] = Yii::app()->user->id;
        }
        return $condition;
    }

    public function find($condition='',$params=array())
    {
        $condition = $this->getUserAccessCondition($condition, $params);
        parent::find($condition, $params);
    }
    // and so on in findAll,  findAttributes...
    // for findByPk you need make some things maybe after find 
    // chek user_id and if is not equal throw access denied exception 
    public function afterFind()
    {
        if ($this->user_id != Yii::app()->user->id) {
            throw new CHttpException(403, 'Access Denied');
        }
    }
}


class UserItem extends UserAccess
{
   //.. rules tableName etc

}
// simple call
$userItem = UserItem::model()->find('name=:name', array(':name' => 'Some search name'));
于 2013-02-05T05:23:43.550 回答