开发者

How do I specify an action's default model

I want to make an action's model to be the current user's if not specified. How to do that?

For example, I have an profile action in user controller. If the url is like /user/profile/3 , It will show profile of user whose id is 3 and if the url is like /user/profile it will show the current user's.

public function actionProfile($id){
                   $model=$this->loadModel($id);
                   $this->render('profile',array(
                        'model'=>$model
                ));
    开发者_StackOverflow中文版    }


How about something like this:

public function actionProfile($id=null)
{
    $id=($id===null?Yii::app()->user->id:$id);
    $model=$this->loadModel($id);
    ...
}


If I understand the question, you are talking about default scopes.

In the model:

public function defaultScope ()
{
    if (Yii::app ()->user->id)
    {
        return array (
            'condition' => 'user_id=' . Yii::app ()->user->id,
        );
    }
    else
    {
        // or whatever
        return array ();
    }
}

Then any query in your controller will use that as a condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜