Understanding our Auto-Generated Code: Model

October 23, 2012

In this section, we’ll be going through our automatically generated code for the Model, Controller and Views. In our case, it’s the Users model, controller and views. First off…The Model

The Model

The Users class extends Yii’s CActiveRecord class, which handles all database record related operations, including CRUD, as well as search and validation. All models generated by Gii have the same methods: tableName, rules, relations, attributeLabels and search; so we’ll go through the methods here, one by one.

The first method is model. It’s a public static function. It returns the static model of the specified AR class, which is a static instance of the same. Every class that extends CActiveRecord must override this method.

public static function model($className=__CLASS__)
    return parent::model($className);

The next method is tableName. It is a public function. It returns the name of the table that the model is associated with.

The next method is rules. It is a public function. It defines validation rules for model attributes (table column names). It is called by Yii’s validate() method before saving a record.

By default, Yii recognises a few of the validation rules that have been defined in the database. For example, if a column has been defined as an integer, Yii will give the model attribute the integerOnly validation rule. If a field is specified as NOT NULL in the database, Yii will give the model attribute the required validation rule. A few of validation rules that are available in Yii include:

  • boolean - validates if the attribute value is a true value or false value
  • date - validates if the attribute value is a valid date, time or datetime value
  • default - sets an attribute with a specified value. No validation is done.
  • email - validates if the attribute is a valid email address (e.g. [email protected])
  • exist - validates if the attribute value exists in the table
  • length - validates if the attribute value is of the specified length
  • numerical - validates if the attribute value is a numerical value
  • match - validates if the attribute value matches the specified regular expression
  • required - validates that the attribute value is not null or empty
  • type - validates that the attribute value is of the specified type
  • unique - validates that the attribute value is unique in the table
  • url - validates that the attribute is a valid url

Note that this is not an exhaustive list. For a more comprehensive list, please look at Yii’s reference guide on model validation here.

As an illustration, we’ll use our Users model example. If you used the schema provided for this tutorial, your rules method should resemble this:

public function rules()
 // NOTE: you should only define rules for those attributes that
 // will receive user inputs.
 return array(
  array('firstName, lastName, userName, email, password, dateCreated, insertedBy, dateModified, updatedBy', 'required'),
  array('status, insertedBy, updatedBy', 'numerical', 'integerOnly'=>true),
  array('firstName, lastName, email', 'length', 'max'=>60),
  array('userName', 'length', 'max'=>15),
  array('password', 'length', 'max'=>255),
  // The following rule is used by search().
  // Please remove those attributes that should not be searched.
  array('userID, firstName, lastName, userName, email, password, status, dateCreated, insertedBy, dateModified, updatedBy', 'safe', 'on'=>'search'),

Since firstName, lastName, userName, email, password, dateCreated, insertedBy, dateModified, updatedBy were all specified as not null, they have been automatically assigned the required attribute.

status, insertedBy, updatedBy were all specified as integers, therefore, their integerOnly attribute was set to true.

firstName, lastName, email all had a length limit of 60, therefore their length attribute was set with max as 60. The same with userName and password, which had limits of 15 & 255 respectively.

The next method is relations. This method returns an array defining relationships between models (and of course tables). Yii uses relations to simplify defining relationships between models, hence easing retrieval of related data. Yii relations support the following Entity Relations:

  • One-to-Many
  • One-to-One
  • Many-to-Many

In Yii’s Active Record, these are defined by:


These relations have been explained in detail here. In our case, the following relations were automatically created by Yii:

return array(
 'studentProfiles'=>array(self::HAS_MANY, 'StudentProfiles', 'userID'),
 'userGroupMappings'=>array(self::HAS_MANY, 'UserGroupMappings', 'userID'),

These relations define the one-to-many relationships between users and studentProfiles, and between users and userGroups. These were created automatically from the foreign keys defined in the schema

We can also create custom relations. This enables us to define relationships even if they are not defined in the database. We’ll see use cases as we continue with this tutorial.

The next method is attributeLabels. These define how the database field names will be displayed in the views. Yii tries to automatically format the database column names to more user-friendly forms. For example, if a database column was named firstName, Yii will detect the camel case, and format this to ‘First Name’. Yii also recognises Pascal case, and a few other commonly used naming conventions. This is an advantage of using standard naming conventions in your database schema design, as well as code. For this project, CamelCase is used.

The last method that is automatically generated is search. This method retrieves a list of models based on the current search/filter conditions. The search and filter conditions can be modified according to your needs. The search function returns a CActiveDataProvider object, which can be used in CGridView to display information. We’ll discuss these more as we progress.

So that’s it for the automatically generated Model. In the next post, we’ll discuss the Controller.