How to create and use a Model in Yii

Source: Internet
Author: User
This article mainly introduces how to create and use a Model in Yii, and analyzes in detail the basic creation techniques, usage methods, and related precautions of the Model in Yii based on the instance form, for more information about how to create and use a Model in Yii, see the following example. We will share this with you for your reference. The details are as follows:

YII implements two models: Form model (CFormModel class) and Active Record Model (lateral verecord class). They all inherit from the CModel class. CFormModel indicates that the data model is input collected from HTML forms and encapsulates all logic (such as form verification and other business logic, applied to form fields ). It can store data in internal storage, or store data in a database with the help of an Active Record.

Database Connection operations

In config/main. php

'DB' => array ('ononstring' => 'MySQL: host = localhost; dbname = Oss', 'default' repare' => true, 'username' => 'root ', 'password' => 'hahaha', 'charset' => 'utf8', // table prefix 'tableprefix' => "oss _"),

Open comments. php must support pdo.

View operation logs

// Display the log information, including the SQL query information array ('class' => 'cweblogroute ',),

Open comments

1. Model based on CActiveRecord

Active Record (AR) is a design pattern that uses object-oriented abstraction to access data. in Yii, each AR object instance can be a CActiveRecord class or its subclass. It encapsulates a row of records in a database table or view, and encapsulates all the logic and information details of the database. most of the business logic must use this model. The values of each column in a row in the database table correspond to a property of the AR object. It maps tables to classes, rows to objects, and columns to object data. That is to say, each instance of the Active Record class represents a row of tables in the database. However, an Active Record class is not only a ing between fields in the database table and attributes in the class. It also needs to process some business logic on the data and define all read/write operations on the database.

1) declare a Model based on the CActiveRecord class

class Post extends CActiveRecord{public static function model($className=__CLASS__){return parent::model($className);}public function tableName(){return '{{post}}';}public function primaryKey(){return 'id';// return array('pk1', 'pk2');}}

2) use the parent class method to complete database operations

(1) Insert:

$post=new Post;$post->title='sample post';$post->content='content for the sample post';$post->create_time=time();$post->save();

(2) Select: several common methods

// find the first row satisfying the specified condition$post=Post::model()->find($condition,$params);// find the row with the specified primary key$post=Post::model()->findByPk($postID,$condition,$params);// find the row with the specified attribute values$post=Post::model()->findByAttributes($attributes,$condition,$params);// find the first row using the specified SQL statement$post=Post::model()->findBySql($sql,$params);$criteria=new CDbCriteria;$criteria->select='title'; // only select the 'title' column$criteria->condition='postID=:postID';$criteria->params=array(':postID'=>10);$post=Post::model()->find($criteria);$post=Post::model()->find(array('select'=>'title','condition'=>'postID=:postID','params'=>array(':postID'=>10),));// find all rows satisfying the specified condition$posts=Post::model()->findAll($condition,$params);// find all rows with the specified primary keys$posts=Post::model()->findAllByPk($postIDs,$condition,$params);// find all rows with the specified attribute values$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);// find all rows using the specified SQL statement$posts=Post::model()->findAllBySql($sql,$params);// get the number of rows satisfying the specified condition$n=Post::model()->count($condition,$params);// get the number of rows using the specified SQL statement$n=Post::model()->countBySql($sql,$params);// check if there is at least a row satisfying the specified condition$exists=Post::model()->exists($condition,$params);

(3) Update

// update the rows matching the specified conditionPost::model()->updateAll($attributes,$condition,$params);// update the rows matching the specified condition and primary key(s)Post::model()->updateByPk($pk,$attributes,$condition,$params);// update counter columns in the rows satisfying the specified conditionsPost::model()->updateCounters($counters,$condition,$params);

(4) Delete

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10$post->delete();// delete the rows matching the specified conditionPost::model()->deleteAll($condition,$params);// delete the rows matching the specified condition and primary key(s)Post::model()->deleteByPk($pk,$condition,$params);

(5) Use transactions

$model=Post::model();$transaction=$model->dbConnection->beginTransaction();try{// find and save are two steps which may be intervened by another request// we therefore use a transaction to ensure consistency and integrity$post=$model->findByPk(10);$post->title='new post title';$post->save();$transaction->commit();}catch(Exception $e){$transaction->rollBack();}

2. Model based on CFormModel

Before writing the HTML required for a form, we need to determine what data we want the user to input and what rules should be met. A model class can be used to record this information. a model is the core of user input and verification.

Based on how we use user input, we can create two types of models. If the input data is collected, used, and discarded, a form model is created. if the input data is saved to the database, we will use active record. Both models inherit the common interfaces of forms defined in their same base class CModel.

1) model class definition

In the following example, a LoginForm model is created to collect user input on the login page. Because the login information is only used for user authentication and does not need to be saved, we use form model to create

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;}

LoginForm declares three attributes (attributes), $ username, $ password, and $ rememberMe.

Used to record the user name, password, and logging options entered by the user. Because the default value of $ rememberMe is false, the corresponding selection box is not checked when the form is displayed.

Tip: We use the name "attributes" instead of "properties" to distinguish them from normal properties.

2) declare verification rules

Once the data submitted by the user is filled into the model, we need to check whether the data is valid before use. This is achieved through a set of rules for the input. In the rulers () method, we configure an array to define verification rules.

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;private $_identity;public function rules(){return array(array('username, password','required'),array('rememberMe', 'boolean'),array('password', 'authenticate'),);}public function authenticate($attribute,$params){if(!$this->hasErrors()) // we only want to authenticate when no input errors{$this->_identity=new UserIdentity($this->username,$this->password);if(!$this->_identity->authenticate())$this->addError('password','Incorrect password.');}}}

The code above indicates that the user name and password must be verified, and the password must be a Boolean rememberMe.

Each rule returned by rules () must follow the following format:

The code is as follows:

Public function ValidatorName ($ attribute, $ params ){...}


Second, Validator enables the class name of the validators. when the rules apply, an instance of the validators class will be created and verified. The additional attributes in the rule, used for the attributes of the initial instance. The validators class must inherit from CValidator

Tip: When specifying rules for the active record model, we can use the special parameter 'on ',

This parameter can be set to 'insert' or 'Update', which can be applied when the rule is inserted or updated. If no life exists, this rule applies when saving () is called.

Third, Validator can pre-define the alias of the validators class. In the preceding example, "required" is the alias of CRequiredValidator. it is used to verify that the attribute cannot be blank. The following is a list of predefined authenticator category names.

The code is as follows:

Array ('content', 'Safe ')

There is also an unsafe rule to specify which attributes are insecure.

The code is as follows:

Array ('permission', 'unsafe ')


Unsafe is not commonly used. this is an exception for the security attributes you previously defined.
5) get verification error
When verification is completed, any possible errors are stored in the model instance. We can call CModel: getErrors () and CModel: getError () to obtain it again. The difference between the two methods is that the first method can return all errors of the specified model attribute, while the second method only returns the first error.

6) attribute tag

When designing a form, we need to display a label for the user input box to prompt the user to enter. Although we can write it in form again, it is more convenient and flexible if we specify it in the corresponding model.

By default, CModel simply returns the attribute name as a tag. This can be customized by overwriting attributeLabels. In the following sections, we will see that specifying tags in the model allows us to create a form more quickly and more efficiently.

I hope this article will help you design php programs based on the yii Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.