Current Location: Home> Latest Articles> Comprehensive Guide to ThinkPHP5 Model Methods: Creation, Query, Insert, Update, Delete

Comprehensive Guide to ThinkPHP5 Model Methods: Creation, Query, Insert, Update, Delete

gitbox 2025-06-24

1. Introduction

In the ThinkPHP5 framework, the model method is an essential tool for handling database operations. This article will provide a detailed explanation of how to use model methods in ThinkPHP5 to help you better understand and apply them.

2. Creating a Model

In ThinkPHP5, you can create a custom model by extending the think\Model class. Typically, create a model folder inside the app directory and add a corresponding model file, such as User.php.

namespace app\index\model;
use think\Model;

class User extends Model
{
    // Define the table name
    protected $table = 'user';
    // Define the primary key
    protected $pk = 'id';
    // Other code ...
}

The custom model class should extend the think\Model class and define the table name and primary key to facilitate subsequent operations.

3. Using the Model

You can conveniently operate on database tables by instantiating the model class or calling its static methods.

3.1 Querying Data

The model supports various query methods such as find(), select(), and where().

Get the user information with id 1:

$user = User::find(1);
echo json_encode($user);

Query all data from the users table:

$users = User::select();
echo json_encode($users);

Query user with id 1 using where condition:

$user = User::where('id', 1)->find();
echo json_encode($user);

3.2 Inserting Data

Create a model object using create(), then call save() to insert the new data.

$user = User::create([
    'name' => 'Tom',
    'email' => '[email protected]',
    'age' => 20
]);
if ($user) {
    echo 'Insert successful';
} else {
    echo 'Insert failed';
}

3.3 Updating Data

Find the data first, modify the properties, then call save() to update.

$user = User::find(1);
$user->name = 'Jerry';
$user->save();

3.4 Deleting Data

Delete the specified record by calling the delete() method.

$user = User::find(1);
$user->delete();

4. Summary

This article introduced the core usages of the model method in ThinkPHP5, including model definition and CRUD operations. Mastering these basics can improve the efficiency of database operations and the maintainability of your code.