Get Created By And Updated By Id

Hi,

I am really a newbie to Yii and I am doing a small application. In that application I have some tables. Like product and discount

The table is like this




=================

    products

=================

+   id           +

+   product_name +

+   cost_price   +

+   selling_price+

+   created_by   +

+   updated_by   +

++++++++++++++++++


=================

    discount

=================

+   id           +

+   discount_type +

+   created_by   +

+   updated_by   +

++++++++++++++++++



Now you can see in those tables I am always keeping created_by and updated_by. I am keeping them to record the changes from whom has created and made updated. So can someone kindly tell me how to get


created_by and updated_by id

and the name? Any help and suggestions will bereally appreciable. Thanks

Create getter methods in your model class to get createdBy and updateBy information something like this code.




public function getCreatedBy(){

   

    $productId = $this->id;// this is your product id.

    $createdBy = User::model()->findByPk($this->created_by)->username; /update this line according to your need to fetch name.


    return $createdBy; 

}



and call this getter in your code like


$model->getCreatedBy();

do the same for updated By.

Or define a relations in your product model with associated keys. then fetch name with a relational tables. :)

i hope it would be helpful for you.

HI,

Thanks for the reply. I have used your code. But can you tell me how to save the id(created_by,updated_by) in the database. I am really newbie to Yii. So kindly tell me how to do this?

it will give you current logged in user id.




$id=Yii::app()->user->id;



So, if you want to save this created by updated by information then you can do it in beforesave method in your model class.something like this




public function beforeSave() {

    if ($this->isNewRecord){

        $this->created_by = Yii::app()->user->id;

        $this->modified_by = Yii::app()->user->id;

 

    }else{

     $this->modified_by = Yii::app()->user->id;

    }

 

    return parent::beforeSave();

}



Hello, where do I need to call the getter method?