Home > PHP Framework > YII > CRUD operations in Yii framework: Simplifying database operations

CRUD operations in Yii framework: Simplifying database operations

WBOY
Release: 2023-06-21 12:34:06
Original
1240 people have browsed it

Yii framework is a high-performance web application development framework based on MVC architecture, with powerful database support and easy-to-use CRUD operations. CRUD operations refer to the operations of adding, deleting, modifying (Create, Read, Update, Delete) to data in the database. In this article, we will take a closer look at CRUD operations in the Yii framework and how you can leverage them to simplify database operations.

1. Model

In the Yii framework, a model is a class associated with a database table, which can be used to operate on data in the database. In the Yii framework, we can quickly generate model classes through the Gii tool. Gii is a code generator that comes with the Yii framework, which can automatically generate basic codes such as controllers, models, forms, and views. Through the model class generated by Gii, we can directly add, delete, modify and query the data in the database.

For example, there is a user table named users in our application. We can generate the corresponding model class through the following command:

yii gii/model --tableName=users
Copy after login

The generated model class is as follows:

namespace appmodels;

use Yii;

/**
 * This is the model class for table "users".
 *
 * @property int $id
 * @property string $username
 * @property string $email
 * @property string $password_hash
 * @property int $status
 * @property string|null $auth_key
 * @property string|null $access_token
 */
class Users extends yiidbActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'users';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['username', 'email', 'password_hash'], 'required'],
            [['status'], 'integer'],
            [['username', 'email', 'password_hash', 'auth_key', 'access_token'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'email' => 'Email',
            'password_hash' => 'Password Hash',
            'status' => 'Status',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
        ];
    }
}
Copy after login

In the model class, we can specify the table name, field rules, field labels and other information. By inheriting the yiidbActiveRecord class, we can easily perform database operations.

2. Query

In the Yii framework, there are many ways to query data. Let’s introduce it through the following aspects:

1. Query all data

$users = Users::find()->all();
Copy after login

You can get a query object by calling the find() method of the model class, and you can get it by calling the all() method. All query results.

2. Query a single piece of data

$user = Users::findOne($id);
Copy after login

You can get a query result by calling the findOne() method of the model class.

3. Conditional query

$users = Users::find()
    ->where(['status' => 1])
    ->orderBy('id DESC')
    ->all();
Copy after login

You can specify query conditions and sorting rules by calling the where() method and orderBy() method of the model class.

3. Add new data

In the Yii framework, adding new data is very simple, you only need to pass an array. For example:

$user = new Users();
$user->username = 'test';
$user->email = 'test@example.com';
$user->password_hash = '123456';
$user->status = 1;
$user->save();
Copy after login

By calling the save() method of the model class, the data will be automatically saved to the database.

4. Update data

In the Yii framework, updating data is also very simple. You only need to query the data you want to update, then modify it and save it. For example:

$user = Users::findOne($id);
$user->username = 'newUsername';
$user->save();
Copy after login

You can get the data to be updated by calling the findOne() method of the model class, then modify the corresponding fields and call the save() method again to update the data.

5. Delete data

Deleting data is similar to updating data. You also need to query the data you want to delete first, and then call the delete() method. For example:

$user = Users::findOne($id);
$user->delete();
Copy after login

The corresponding record can be deleted from the database by calling the delete() method of the model class.

6. Summary

In this article, we introduced in detail the CRUD operations in the Yii framework and how to use them to simplify database operations. By using the methods of querying, adding, updating, and deleting data provided by the Yii framework, we can avoid handwriting SQL statements, improve development efficiency, and make our coding simpler and clearer.

The above is the detailed content of CRUD operations in Yii framework: Simplifying database operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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