background preloader

Yii Data Modeling

Facebook Twitter

Models. A model is an instance of CModel or a class that extends CModel. Models are used to keep data and their relevant business rules. A model represents a single data object. It could be a row in a database table or an html form with user input fields. Each field of the data object is represented by an attribute of the model.

Yii implements two kinds of models: Form models and active records. A form model is an instance of CFormModel. Active Record (AR) is a design pattern used to abstract database access in an object-oriented fashion. For the best practices on defining your models check Best MVC Practices, Model section. Creating Model. Before writing the HTML code needed by a form, we should decide what kind of data we are expecting from end users and what rules these data should comply with. A model class can be used to record these information. A model, as defined in the Model subsection, is the central place for keeping user inputs and validating them.

Depending on how we make use of the user input, we can create two types of model. If the user input is collected, used and then discarded, we would create a form model; if the user input is collected and saved into database, we would use an active record instead. Both types of model share the same base class CModel which defines the common interface needed by form. Note: We are mainly using form models in the examples of this section. 1. Below we create a LoginForm model class used to collect user input on a login page. Class LoginForm extends CFormModel{ public $username; public $password; public $rememberMe=false; } 2. 3. Declaring Safe Attributes 4. 5. 6. CModel. Look up a class, method, property or event CModel is the base class providing the common features needed by data model objects. CModel defines the basic framework for data models that need to be validated. Public Properties Hide inherited properties Property Details Returns all attribute values. public array getErrors(string $attribute=NULL) Returns the errors for all attribute or a single attribute.

Returns an iterator for traversing the attributes in the model. Returns the attribute names that are safe to be massively assigned. Returns the scenario that this model is used in. Scenario affects how validation is performed and which attributes can be massively assigned. A validation rule will be performed when calling validate() if its 'except' value does not contain current scenario value while 'on' option is not set or contains the current scenario value. And an attribute can be massively assigned if it is associated with a validation rule for the current scenario. Method Details. Model Rules. This is a reference to be used for Model rule validation and is compiled from the Yii documentation and code. The purpose is to have all the information gathered in one place instead of scattered. This reference is not an intro. See The Definitive Guide to Yii, Declaring Validation Rules for a tutorial. How validation works ¶ The CModel class uses a method named CModel::rules() to return an array with the rules for validation. public function rules(){ return array( array('username, password', 'required'), array('password_repeat', 'required', 'on'=>'register'), array('password', 'compare', 'compareAttribute'=>'password_repeat', 'on'=>'register'), ); } The code above is an example of what the CModel::rules() function may look like.

These rules are applied by the CModel::validate() method which returns a boolean value. Parameters of a validator ¶ array( 'attribute list', 'validator name', 'on'=>'scenario name', 'message'=>'The attribute didn\'t validate! ' Choice of validators ¶ Scenarios ¶ CModel Rules. Look up a class, method, property or event CModel is the base class providing the common features needed by data model objects. CModel defines the basic framework for data models that need to be validated. Public Properties Hide inherited properties Property Details Returns all attribute values. public array getErrors(string $attribute=NULL) Returns the errors for all attribute or a single attribute. Returns an iterator for traversing the attributes in the model.

Returns the attribute names that are safe to be massively assigned. Returns the scenario that this model is used in. Scenario affects how validation is performed and which attributes can be massively assigned. A validation rule will be performed when calling validate() if its 'except' value does not contain current scenario value while 'on' option is not set or contains the current scenario value. And an attribute can be massively assigned if it is associated with a validation rule for the current scenario. Method Details.

Yii Data Validation

Scenario explanation. Validation scenarios. February 16th, 2009 As of Yii 1.0.2 you may now define validation scenarios. This is very useful if for instance you have multiple places in your application that you validate a model, but in each instance you may want different validation rules. For instance, perhaps in your user registration form you want to have the “username”, “email” and “password” fields to be required, while on your “user recovery” page, you only want the “email” field to be required. You may see a problem here. If you set all the fields to be required, then your user recovery page won’t work, as it does not allow a user to supply neither a password nor a username. The perfect solution to this are validation scenarios. <? With this setup Yii will be able to tell which fields are required in which scenarios.

Now when you wish to run validation under a specific scenario you must define it in when calling CModel::validate(), as so <? So the above example will validate the user under the ‘register’ scenario. Active Record. Although Yii DAO can handle virtually any database-related task, chances are that we would spend 90% of our time in writing some SQL statements which perform the common CRUD (create, read, update and delete) operations.

It is also difficult to maintain our code when they are mixed with SQL statements. To solve these problems, we can use Active Record. Active Record (AR) is a popular Object-Relational Mapping (ORM) technique. Each AR class represents a database table (or view) whose attributes are represented as the AR class properties, and an AR instance represents a row in that table. Common CRUD operations are implemented as AR methods. As a result, we can access our data in a more object-oriented way. $post=new Post; $post->title='sample post'; $post->content='post body content'; $post->save(); In the following we describe how to set up AR and use it to perform CRUD operations. Note: AR is not meant to solve all database-related tasks. 1.

Support for AR is limited by DBMS. 2. 3. 4. Relational Active Record. We have already seen how to use Active Record (AR) to select data from a single database table. In this section, we describe how to use AR to join several related database tables and bring back the joint data set. In order to use relational AR, it is recommended that primary-foreign key constraints are declared for tables that need to be joined. The constraints will help to keep the consistency and integrity of the relational data. For simplicity, we will use the database schema shown in the following entity-relationship (ER) diagram to illustrate examples in this section.

ER Diagram Info: Support for foreign key constraints varies in different DBMS. 1. Before we use AR to perform relational query, we need to let AR know how one AR class is related with another. Relationship between two AR classes is directly associated with the relationship between the database tables represented by the AR classes. Declaring relationship in AR involves overriding the relations() method of CActiveRecord. Or. CActiveRecord. Look up a class, method, property or event CActiveRecord is the base class for classes representing relational data. It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique. Please check the Guide for more details about this class. Protected Methods Hide inherited methods Events Hide inherited events Property Details Returns all column attribute values. CommandBuilder Returns the command builder used by this AR. the default database connection for all active record classes. Returns the database connection used by active record.

Returns the query criteria associated with this model. Returns if the current record is new. Returns the meta-data for this AR Returns the old primary key value. Returns the primary key value. Returns the table alias to be used by the find methods. Returns the metadata of the table that this AR belongs to Method Details Source Code:framework/db/ar/CActiveRecord.php#210 (show) return parent::__call($name,$parameters);} $this->init(); CActiveRecord Relationships. Look up a class, method, property or event CActiveRecord is the base class for classes representing relational data.

It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique. Please check the Guide for more details about this class. Protected Methods Hide inherited methods Events Hide inherited events Property Details Returns all column attribute values. CommandBuilder Returns the command builder used by this AR. the default database connection for all active record classes. Returns the database connection used by active record. Returns the query criteria associated with this model.

Returns if the current record is new. Returns the meta-data for this AR Returns the old primary key value. Returns the primary key value. Returns the table alias to be used by the find methods. Returns the metadata of the table that this AR belongs to Method Details Source Code:framework/db/ar/CActiveRecord.php#210 (show) return parent::__call($name,$parameters);} $this->init(); CFormModel. Look up a class, method, property or event CFormModel represents a data model that collects HTML form inputs. Unlike CActiveRecord, the data collected by CFormModel are stored in memory only, instead of database. To collect user inputs, you may extend CFormModel and define the attributes whose values are to be collected from user inputs.

You may override rules() to declare validation rules that should be applied to the attributes. Method Details Source Code:framework/web/CFormModel.php#36 (show) public function __construct($scenario=''){ $this->setScenario($scenario); $this->init(); $this->attachBehaviors($this->behaviors()); $this->afterConstruct();} Constructor.

Source Code:framework/web/CFormModel.php#60 (show) Returns the list of attribute names. Initializes this model.