PHP development framework YiiFramework tutorial (26) database-ActiveRecord example

Source: Internet
Author: User
Tags php foreach
PHP development framework YiiFramework tutorial (26) database-ActiveRecord example

Use Java or. net write database applications, many people have used Hibernate (or nhib.pdf) can greatly simplify database programming, and read and write the database (ORM) as an object, Yii provides Active Record (AR) it is also a popular object-relational ing (ORM) technology. Each AR class represents a data table (or view). the column of a data table (or view) is embodied as a class attribute in the AR class. an AR instance represents a row in the table. Common CRUD operations are implemented as AR methods. Therefore, we can access data in a more object-oriented way.

Here, modify the Yii Framework Development Tutorial (24) database-DAO example to see how to read the Employee table using Active Record.

To access a data table, we first need to define an AR class by integrating CActiveRecord. Each AR class represents a separate data table, and an AR instance represents a row in that table.

Since AR classes are often referenced in multiple places, we can import the entire directory containing AR classes instead of importing them one by one. For example, if all our AR files are in the protected/models Directory, we can configure the application as follows:

'Import' => array (
'Application. models .*',
). In this example, the Employee class is defined as follows:

Class Employee extends CActiveRecord
{
Public static function model ($ className =__ CLASS __)
{
Return parent: model ($ className );
}

Public function tableName ()
{
Return 'employee ';
}
}

The values of columns in the row of the data table can be accessed as attributes of the corresponding AR instance. For example, $ employee-> EmployeeId can access the EmployeeId field of the Employee.

In this example, only the Employee table is read and the indexAction method of SiteController is modified:

Public function

ActionIndex ()
{

$ Model = Employee: model ()-> findAll ();

$ This-> render ('index', array (
'Model' => $ model,

));
}

You can see that only one line of code: Employee: model ()-> findAll () can be used to read the database table and assign values, to see the corresponding Display Record code:

{

Echo 'employeeid: '. $ employee-> EmployeeId .'
';
Echo 'first Name: '. $ employee-> FirstName .'
';
Echo 'last Name: '. $ employee-> LastName .'
';
Echo 'Title: '. $ employee-> Title .'
';
Echo 'address: '. $ employee-> Address .'
';
Echo 'email: '. $ employee-> Email .'
';
Echo '----------------------
';
}

?>

We can see that using AR can directly access a field value through the field name (case sensitive) of the database table, without the need to define the class Employee, thus greatly simplifying the code.

As mentioned above, the CModel has two subclasses: FormModel and CActiveRecord. CActiveRecord defines the CRUD method for database access, for example

Create record

To insert a new row into a data table, we need to create an AR class instance, set its attributes related to the table columns, and call the save () method to complete the insertion.

$ Employee = new Employee;
$ Employee-> FirstName = 'James ';
$ Employee-> LastName = 'shen ';
...
$ Employee-> save ();

If the table's primary key is auto-incrementing, the AR instance will contain an updated primary key after the insertion is complete. If a column is defined by a static default value (such as a string or number) in the table structure.

Read records

To read data from a data table, we can call one of the find series methods in the following way:

// Find the first row in the result that meets the specified condition
$ Post = Post: model ()-> find ($ condition, $ params );
// Find the row with the specified primary key value
$ Post = Post: model ()-> findByPk ($ postID, $ condition, $ params );
// Search for rows with the specified property value
$ Post = Post: model ()-> findByAttributes ($ attributes, $ condition, $ params );
// Use the specified SQL statement to find the first row in the result
$ Post = Post: model ()-> findBySql ($ SQL, $ params); as shown above, we call the find method through Post: model. Remember that the static method model () is required for each AR class. This method returns an AR instance in the object context used for classification class-level methods (something similar to static class methods.

If the find method finds a row that meets the query conditions, it returns a Post instance. the instance attributes contain the values of the corresponding columns in the row of the data table. Then we can read the loaded value like reading the attributes of a common object, such as echo $ post-> title ;.

If nothing is found in the database using the given query conditions, the find method returns null.

When we call find, we use $ condition and $ params to specify the query conditions. $ Condition can be the WHERE string in the SQL statement, and $ params is a parameter array. The value should be bound to a placeholder in $ condation.

Update record

After the AR instance is filled with column values, we can change them and save them back to the data table.

$ Post = Post: model ()-> findByPk (10 );
$ Post-> title = 'new post title ';
$ Post-> save (); // save the changes to the database deletion record

If an AR instance is filled with a row of data, we can also delete this row of data.

$ Post = Post: model ()-> findByPk (10); // assume that there is a post whose ID is 10.
$ Post-> delete (); // delete this row from the data table. Note that the AR instance remains unchanged after deletion, but the corresponding row in the data table is no longer available.

For other information, see the Yii Chinese document (http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.ar.

The result in this example is as follows:


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.