Home > PHP Framework > ThinkPHP > body text

Let's talk about how to use models in ThinkPHP 5.0

PHPz
Release: 2023-04-21 11:28:34
Original
1319 people have browsed it

ThinkPHP 5.0 is one of the most widely used PHP development frameworks in China. It has not only made a lot of optimizations and improvements in the core code, but also added many new functions and features, among which the model has also been greatly improved. Big upgrade. This article will introduce in detail how to use models in ThinkPHP 5.0.

1. What is a model

A model is simply a data operation class used to operate the database. In ThinkPHP, the model encapsulates the data table, allowing convenient and fast operations on the data table. When creating a model, you only need to inherit Think\Model instead of writing a large number of queries and SQL statements.

2. Create a simple model

  1. First create a model in ThinkPHP 5.0

In ThinkPHP 5.0, creating a model is very simple. You only need to create a new model directory in the application directory, and then create a new file named User.php in the model directory. The code is as follows:

<?php

namespace app\model;

use think\Model;

class User extends Model
{
}
Copy after login
  1. Connect to the database

ThinkPHP 5.0 uses PDO to connect to the database by default, and the database connection information is configured in the database.php file in the application directory. After the connection is successful, you can perform corresponding operations in the model.

  1. Basic CRUD operations of the model

In ThinkPHP 5.0, the basic CRUD operations of the model have been encapsulated and can be called directly. Take the User model as an example to demonstrate the most common CRUD operations:

(1) Insert data

$user = new User();

$user->name = 'Tom';
$user->age = 20;

$user->save();
Copy after login

The above is the most common way to insert data, instantiate a User object, and then pass the attributes method to assign values ​​to the object, and finally call the save() method to save the data to the database.

(2) Delete data

User::destroy(1);
Copy after login

The 1 here is the ID of the data to be deleted. If you want to delete multiple pieces of data, you can pass an array. You can also use the where method for conditional deletion.

(3) Query data

// 查询所有数据
$users = User::all();

// 根据条件查询单条数据
$user = User::where('name', 'Tom')->find();

// 根据条件查询多条数据
$users = User::where('age', '>', 18)->select();
Copy after login

(4) Update data

$user = User::get(1);

$user->name = 'Jack';

$user->save();
Copy after login

That is, first query the data to be modified, and then save it to the database through the save() method after modifying the data middle.

3. Model correlation operations

In actual development, it is often necessary to perform complex joint queries and correlation operations on multiple data tables. The ThinkPHP 5.0 model provides rich association operations that can quickly solve association problems between tables.

  1. One-to-one association

In ThinkPHP 5.0, there are three ways of one-to-one association:

(1) Association model attributes

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('Profile');
    }
}

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo('User');
    }
}

$user = User::get(1);

$profile = $user->profile;
Copy after login

In the above code, the User model is associated with the Profile model through the hasOne() method, and then the $user->profile attribute is called to obtain the associated data.

(2) Related query

$user = User::with('profile')->select();

$profile = $user->profile;
Copy after login

In the above code, the related query is directly performed through the with() method, and then the $user->profile attribute is called to obtain the related data.

(3) Integrated query

$user = User::field('name')
            ->join('profile', 'profile.user_id=user.id')
            ->select();

$profile = $user->profile;
Copy after login

In the above code, the User table and Profile table are connected through the join() method, and then the fields of the Profile table can be obtained in the field expression.

  1. One-to-many association

In ThinkPHP 5.0, there are also three ways of one-to-many association:

(1) Attributes of the associated model

class User extends Model
{
    public function books()
    {
        return $this->hasMany('Book');
    }
}

class Book extends Model
{
    public function user()
    {
        return $this->belongsTo('User');
    }
}

$user = User::get(1);

$books = $user->books;
Copy after login

In the above code, the User model is associated with the Book model through the hasMany() method, and then the $user->books attribute is called to obtain the associated data.

(2) Related query

$user = User::with('books')->select();

$books = $user->books;
Copy after login

In the above code, the related query is directly performed through the with() method, and then the $user->books attribute is called to obtain the related data.

(3) Integrated query

$user = User::field('name')
            ->join('book', 'book.user_id=user.id')
            ->select();

$books = $user->books;
Copy after login

In the above code, the User table is connected to the Book table through the join() method, and then the fields of the Book table can be obtained in the field expression.

  1. Many-to-many association

Many-to-many association also has three methods in ThinkPHP 5.0:

(1) Main model association model attribute

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('Role');
    }
}

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('User');
    }
}

$user = User::get(1);

$roles = $user->roles;
Copy after login

In the above code, the User model is associated with the Role model through the belongsToMany() method, and then the $user->roles attribute is called to obtain the associated data.

(2) Query the intermediate tables separately

$user = User::get(1);

$roles = $user->roles()
            ->where('status', '1')
            ->select();
Copy after login

In the above code, call the $user->roles() method to obtain the intermediate table, and then use the where() method to perform conditional query.

(3) Intermediate table integration query

$user = User::field('name,role.name as rolename')
            ->join('user_role','user_role.user_id=user.id')
            ->join('role', 'user_role.role_id=role.id')
            ->select();

$roles = $user->roles;
Copy after login

In the above code, the User table, UserRole table and Role table are connected through the join() method, and then the Role can be obtained in the field expression table fields.

4. Model events

ThinkPHP 5.0 model events provide many useful hooks in the life cycle of the model, allowing us to operate and process data at different times and stages. Conveniently implement functions such as data verification, automatic filling, and data updating. Commonly used events include the following:

(1) Pre-query event

class User extends Model
{
    protected static function onBeforeFind($query)
    {
        // before find event
    }
}
Copy after login

In the above code, the pre-query event is added through the onBeforeFind() method.

(2) Pre-insert event

class User extends Model
{
    protected static function onBeforeInsert($data)
    {
        // before insert event
    }
}
Copy after login

In the above code, add the pre-insert event through the onBeforeInsert() method.

(3) Pre-update event

class User extends Model
{
    protected static function onBeforeUpdate($data)
    {
        // before update event
    }
}
Copy after login

In the above code, the pre-update event is added through the onBeforeUpdate() method.

(4) Event before deletion

class User extends Model
{
    protected static function onBeforeDelete($data)
    {
        // before delete event
    }
}
Copy after login

In the above code, the event before deletion is added through the onBeforeDelete() method.

5. Summary

Through the introduction of this article, we can see that the model in ThinkPHP 5.0 is very simple to use and supports CRUD operations and commonly used related queries. At the same time, model events can easily implement functions such as data verification, automatic filling, and data updating. Through the use of in-depth learning models, development efficiency can be improved and the project development process can be accelerated.

The above is the detailed content of Let's talk about how to use models in ThinkPHP 5.0. For more information, please follow other related articles on the PHP Chinese website!

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