


PHP development framework Yii Framework tutorial (26) Database-Active Record example
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.*', ),
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 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, ));}
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 '----------------------';} ?>
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();
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(); // 将更改保存到数据库删除记录
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 实例仍然不变,但数据表中相应的行已经没了
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:
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.
![SCNotification has stopped working [5 steps to fix it]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on
