two models one controller

hello,

i have a situation that i could not find a solution.

i have two models User & Profile

they have a relation in User model like this:


'profile' => array(self::HAS_ONE, 'Profile', 'id'),

what im trying to do is:

after login -if user profile is empty- im redirecting users to a setup page which has both attribs from User & Profile models.

after login im running this action:


  public function actionMain()

        {   

                $user = User::model()->with('profile')->findByPk(Yii::app()->user->id);

                if ($user->profile)

                        $this->render('main', array('user'=>$user));

                else

                        $this->render('profile', array('user'=>$user, 'update'=>false));


        }

but since this is being called from User controller im having errors in the view for Profile model`s attribs.

how can i update both models in a single view?

ok i got it. how i could not… >:(

i changed action like this:


        public function actionMain()

        {       

                $user = User::model()->with('profile')->findByPk(Yii::app()->user->id);

                if ($user->profile)

                        $this->render('main', array('user'=>$user));

                else {

                        $prof = new Profile;

                        $this->render('profile', array('user'=>$user, 'prof'=>$prof, 'update'=>false));

                }

        }

then everything is ok for now :)

The relationship between models and controllers does not have to be 1-1.

If your user does not have a profile at the time of or you have a user, but no profile, then define a new one and attach it to the user before viewing.




$user = User::model()->findByPk(123);

empty($user->profile) and $user->profile = new Profile();


if($_POST['User']) {

  if($user->validate()) {

    if($user->save()) {

      $user->profile->user_id = $user->id;

      if($user->profile->validate()) {

        $user->profile->save();

      }

      ...

    }

  }

}


$this->render('user', compact('user'));



This way a user is presented with a blank form for editing if he no profile, and a filled one if his profile exists. Am I answering your question? …

thanks datashaman

thats actually what im trying to do :)