PHP development framework Yii Framework tutorial (26) Database-Active Record example

黄舟
Release: 2023-03-05 09:06:02
Original
1749 people have browsed it

Use Java or .Net to write database applications. Many people have used Hibernate (or NHibernate), which can greatly simplify database programming. To read and write databases (ORM) in the form of objects, Active Record (AR) provided by Yii It is also a popular object-relational mapping (ORM) technology. Each AR class represents a data table (or view), the columns of the data table (or view) are reflected in the AR class as attributes 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.

Modify the Yii Framework Development Tutorial (24) database-DAO example here 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 class files are in the protected/models directory, we can configure the application as follows:

'import'=>array(
'application.models.*',
),
Copy after login

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';
}
}
Copy after login

The columns in the data table rows Values ​​can be accessed as properties of the corresponding AR instance. For example, $employee->EmployeeId can access the EmployeeId field of Employee.

This example only reads the Employee table and modifies the indexAction method of SiteController:

public function
actionIndex(){$model = Employee::model()->findAll();
$this->render('index', array('model' => $model,
));}
Copy after login

You can see that only one line of code Employee::model()->findAll() can read the database. Table and assignment function, let’s take a look at the corresponding code for displaying records:

{
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 '----------------------';}
?>
Copy after login

You can see that using AR, you can directly access a field value through the field name of the database table (case-sensitive), without having to use it in the class. Employee definition, thus greatly simplifying the code.

When I introduced Model earlier, I said that CModel has two subclasses, one is FormModel, and the other is CActiveRecord. CActiveRecord defines CRUD methods for database access, such as

Create records

To insert new rows into the data table, we need to create an instance of the corresponding AR class, set its properties related to the columns of the table, and then call the save() method to complete the insertion

$employee=new Employee;
$employee->FirstName='James';
$employee->LastName='Shen';
...
$employee->save();
Copy after login

If the primary key of the table is auto-incrementing, and after the insert is complete, the AR instance will contain an updated primary key. If a column is defined in the table structure using a static default value (eg a string, a number).

Read records

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

// Find records that meet the specified conditions The first row in the result
$post=Post::model()->find($condition,$params);
// Find the row with the specified primary key value
$post= Post::model()->findByPk($postID,$condition,$params);
// Find rows with specified attribute values
$post=Post::model()->findByAttributes( $attributes,$condition,$params);
// Find 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 through Post::model(). Remember that the static method model() is required for every AR class. This method returns an AR instance in the object context for accessing class-level methods (something like static class methods).

If the find method finds a row that meets the query conditions, it will return a Post instance whose attributes contain the values ​​of the corresponding columns in the data table row. We can then read the loaded value like a normal object property, for example echo $post->title;.

The find method will return null if nothing is found in the database using the given query criteria.

When calling find, we use $condition and $params to specify the query conditions. Here $condition can be a WHERE string in the SQL statement and $params is an array of parameters whose values ​​should be bound to the placeholders in $condation.

Update Records

After the AR instance has populated the 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(); // 将更改保存到数据库删除记录
Copy after login

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

$post=Post::model()->findByPk(10); // 假设有一个帖子,其 ID 为 10
$post->delete(); // 从数据表中删除此行注意,删除之后, AR 实例仍然不变,但数据表中相应的行已经没了
Copy after login

For other information, please refer to Yii Chinese documentation (http://www.yiiframework.com/doc/guide /1.1/zh_cn/database.ar), which will not be repeated in detail here.

This example displays the results:

PHP development framework Yii Framework tutorial (26) Database-Active Record example

The above is the content of the PHP development framework Yii Framework tutorial (26) database-Active Record example. For more related content, please Follow the PHP Chinese website (www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template