Stephen
Stephen

Reputation: 2540

How to update a foreign key without using the controller? - yii, php

I've recently created a database that has a table of a user, mobile_accounts, and paylists. Both the paylists and the mobile_accounts link back to the user and both have the foreign id "user_id". When I am letting users create their own paylists or mobile_accounts, I am using a function that I created in the user model called "addUserId". I call that function in each specific controller (i.e. paylists or in mobile_accounts) passing in both the current model and the user_id. This is working for me fine, but it seems like a bit of a work-around system. Am I missing something very simple in terms of how to update my database with a foreign key? Or will I just have to keep on creating functions like this in the future?

Here is the code in the Paylist controller

public function actionCreate()
{
    $model=new Paylist;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Paylist']))
    {
        $model->attributes=$_POST['Paylist'];
        if($model->save())
            // adds the current UserId to the table
            User::model()->addUserId($model);
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

And here is the code in the User model

// adds the user id to your data table, takes in the user id and adds it to specified model 
public function addUserId($model)
{  
    $accountid = $model->id;
    $current_email = Yii::app()->user->getId();
    // gets the current id of the user 
    $user = User::model()->findByAttributes(array('email'=>$current_email));
    // extracts out the id of the current user 
    $user_id = $user->id; 
    $model->updateByPk($accountid,array('user_id'=>$user_id)); 

}

Upvotes: 1

Views: 108

Answers (1)

Goodnickoff
Goodnickoff

Reputation: 2267

You can use CActiveRecord::beforeSave() method in your models:

public function beforeSave(){
   if($this->isNewRecord){
       User::model()->addUserId($this);
   }
   return parent::beforeSave();
}

And change addUserId method:

public function addUserId($model)
{  
    $accountid = $model->id;
    $current_email = Yii::app()->user->getId();
    $user = User::model()->findByAttributes(array('email'=>$current_email));
    $model->user_id = $user->id; ; // just set user_id attribute
}

Also you can implement method getCurrentUserId in User model which returns current user id and invoke this method in beforeSave:

public function beforeSave(){
   if($this->isNewRecord){
       $this->user_id = User::getCurrentUserId();
   }
   return parent::beforeSave();
}

Upvotes: 1

Related Questions