Current Location: Home> Latest Articles> How to Use ORM in ThinkPHP for Database Operations

How to Use ORM in ThinkPHP for Database Operations

gitbox 2025-06-27

Using ORM for Database Operations in ThinkPHP

ThinkPHP is an open-source PHP framework based on the MVC design pattern. It includes a powerful built-in ORM (Object-Relational Mapping) system that greatly simplifies database interactions. With ORM, developers can interact with databases using object-oriented syntax rather than writing raw SQL queries.

In ThinkPHP, the core of ORM operations lies in creating models. By defining a model class, developers can easily perform CRUD operations (Create, Read, Update, Delete) on corresponding database tables.

Creating a Model

A model in ThinkPHP is an abstraction of a database table. Typically, model classes extend from a base model provided by the framework. Here's how to define a user model:


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

class User extends Model
{
    // Define table name
    protected $name = 'user';
}

This code defines a User model that maps to the user table in the database. By extending the Model class and specifying the table name, the model is linked to the database schema.

Model Operations

Once the model is set up, it can be used for various database operations, including querying, inserting, updating, and deleting records.

Querying Data

Querying is one of the most common uses of ORM. Below are examples of different query types.

Query All Records


// Instantiate the User model
$user = new User();
// Retrieve all user records
$result = $user->select();

This snippet demonstrates how to retrieve all rows from the user table using the model.

Conditional Query


// Retrieve users aged 18 or older
$result = $user->where('age', '>=', 18)->select();

The where method sets the condition for filtering records, in this case returning users whose age is 18 or older.

Inserting Data

In addition to querying, models can be used to insert new records. Here's an example of how to add a new user:


// Create a new user instance
$newUser = new User();
$newUser->name = 'John';
$newUser->age = 20;
$newUser->save();

This code creates a new User object, assigns values to its properties, and then saves it to the database using the save method.

Conclusion

This article covered the basic steps for using ORM in ThinkPHP to handle database operations. It demonstrated how to create a model, query records with or without conditions, and insert new records into the database. ThinkPHP's ORM capabilities streamline the data handling process, reduce the need for manual SQL, and improve overall development efficiency. For PHP developers building small to medium-sized web applications, ThinkPHP provides a clear and practical ORM solution.