This tutorial explains how to automatically fill in the field values in the model without using code.
This tutorial explains how to automatically fill in the field values in the model without using code.
Scenario
I am working on a management panel for a large project. almost all database tables contain four identical fields.
CreatedDate(Record creation time)
CreatedIp(The IP address of the creator)
UpdatedDate(Record the update time)
UpdatedIp(Record the updated IP address)
I have used the gii tool to create CURD. Now I need to modify each model/controller to implement the CRUD operation for the newly added four fields. A better way is to write the code to a place where other models can inherit and use it.
Create a new model:
Use the following code to create a new modelMasterAdmin, This file should be placed in the directory of the public model.
You can understand it in the comments of the code.
IsNewRecord) // only execute {if ($ this-> hasAttribute ('createddate') when creating a record ')) // if the model has the createDate field $ this-> createdDate = new CDbExpression ('Now ()'); // set the value of createdDate if ($ this-> hasAttribute ('createdip') // if the model has the createdIp field $ this-> createdIp = CHttpRequest: getUserHostAddress (); // Set the user's IP} if ($ this-> hasAttribute ('updateddate') // if the model has the updatedDate field $ this-> updatedDate = new CDbExpression ('Now () '); // Set the updatedDate value if ($ this-> hasAttribute ('updatedip ') // if the model has the updatedIp field $ this-> updatedIp = CHttpRequest: getUserHostAddress (); // Set the user's IP return parent: beforeSave () ;}}?>
Maybe not all models have these four fields. you can still use this model.HasAttributeThe method is automatically determined.
Use the newly added model:
All the models you see are inherited in the following way.
class User extends CActiveRecord {
Use the following code to modify it so that it inherits the newly created model. Don't worry about CActiveRecord, because the newly created MasterAdmin has inherited it.
class User extends MasterAdmin {
If you do not want to modify the code as you do, you can modify the template generated by CURD.
_Path: MyProject \ framework \ gii \ generators \ model \ ModelCode. php
Modify
public $baseClass='CActiveRecord';
Is
public $baseClass='MasterAdmin';
Now you don't need to write any code about the four fields, because MaserAdmin will do it for you.
Click here to get