PHP Development Framework Yii Framework Tutorial (26) Database-active Record sample

Source: Internet
Author: User
Tags php foreach static class first row yii

Using Java or. Net Write database applications, many people have used hibernate (or nhibernate) to greatly simplify the database programming, while the object of the way to read and write the database (ORM), Yii provided by the active record (AR) is also a popular Object-Relational mapping (ORM) technology. Each AR class represents a data table (or view), and the columns of the datasheet (or view) are reflected in the AR class as properties of the class, and an AR instance represents a row in the table. Common CRUD operations are implemented as AR methods. Therefore, we can access the data in a more object-oriented way.

Here, modify the Yii Framework Development Tutorial (24) Database-dao example to see how an employee table is read using an active record.

To access a data table, we first need to define an AR class through an integrated Cactiverecord. Each AR class represents a single data table, and an AR instance represents a row in that table.

Since AR classes are often referenced in multiple places, we can import an entire directory containing AR classes instead of importing them all at once. For example, if all of our AR class files are in the Protected/models directory, we can configure the application as follows:

' Import ' =>array (     
    ' application.models.* ',     
    ),

This example defines the employee class as follows:

Class Employee extends Cactiverecord     
{public     
    static function model ($className =__class__)     
    {     
        return Parent::model ($className);     
         
    Public Function tablename ()     
    {return     
        ' Employee ';     
    }     
}

The value of a column in a datasheet row can be accessed as a property of the corresponding AR instance. For example $employee->employeeid can access the EmployeeId field of employee.

This example simply reads the employee table and modifies the Sitecontroller Indexaction method:

Public Function 

Actionindex ()     
{     
         
    $model = Employee::model ()->findall ();     

    $this->render (' index ', array (     
        ' model ' => $model     

        );     
}

You can see the code for the corresponding display record by just one line of code Employee::model ()->findall () to read the database table and assign the function:

<?php foreach ($model as $employee)     
{

    echo ' EmployeeId: '. $employee->employeeid. ' <br/> ';     
    Echo ' Name: '. $employee->firstname. ' <br/> ';     
    Echo ' last Name: '. $employee->lastname. ' <br/> ';     
    Echo ' Title: '. $employee->title. ' <br/> ';     
    Echo ' Address: '. $employee->address. ' <br/> ';     
    Echo ' Email: '. $employee->email. ' <br/> ';     
    Echo '----------------------<br/> ';     

 >

You can see that using AR to access a field value directly from the field name (case-sensitive) of the database table without having to define it in class employee greatly simplifies the code.

In the previous introduction model said Cmodel has two subclasses, one is Formmodel, the other is Cactiverecord, Cactiverecord defines the database access of the Crud method, such as

Create a record

To insert a new row into the datasheet, we create an instance of the corresponding AR class, set its properties related to the column of the table, and then call the Save () method to finish inserting

$employee =new employee;
$employee->firstname= ' James ';
$employee->lastname= ' Shen ';
...     
$employee->save ();

If the primary key of the table is self increasing, the AR instance will contain an updated primary key after the insertion completes. If a column has a static default value (such as a string, a number) defined in the table structure.

Reading Records

To read data in a data table, we can call one of the Find series methods in the following ways

Finds the first row in the result that satisfies the specified condition     
$post =post::model ()->find ($condition, $params);     
Finds the row with the specified primary key value     
$post =post::model ()->findbypk ($postID, $condition, $params);     
Finds the row with the specified property value     
$post =post::model ()->findbyattributes ($attributes, $condition, $params);     
Finds the first row in the result through the specified SQL statement     
$post =post::model ()->findbysql ($sql, $params);

As shown above, we call the Find method via Post::model (). Keep in mind that static method model () is required for each AR class. This method returns an AR instance in the object context that is used to access the class-level method (something similar to a static class method).

If the Find method finds a row that satisfies the query criteria, it returns a Post instance whose properties contain the value of the corresponding column in the datasheet row. We can then read the loaded values like the properties of normal objects, such as Echo $post->title;.

If nothing is found in the database using the given query criteria, the Find method returns NULL.

When we call find, we specify the query criteria using $condition and $params. Here $condition can be a where string in an SQL statement, $params An array of arguments, where the values should be bound to placeholders in the $condation.

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.