Current Location: Home> Latest Articles> How to Query Data and Add Fields in ThinkPHP

How to Query Data and Add Fields in ThinkPHP

gitbox 2025-07-02

Introduction

ThinkPHP is an open-source PHP-based web framework widely used in web development. When performing database operations, querying data from the database and processing the results is a common task. This article will explain how to query data in ThinkPHP and add custom fields to the query results.

Data Query

In ThinkPHP, you can perform data queries using models. Here’s a simple example of querying data:

Create the Model

First, you need to create a model file to define the relationship between the model and the database table. In ThinkPHP, you can use the command-line tool to automatically generate model files with the following command:

php think make:model User

This command will generate a `User.php` model file under the `app/model` directory.

Query Data

Within the generated model file, use the `select` method to query the database. Here’s an example that queries the `users` table:

$users = User::select();
foreach ($users as $user) {
    echo $user->name;
}

In the above code, `User::select()` queries all the data from the `users` table and stores the result in the `$users` variable. The `foreach` loop then iterates through each user and outputs their `name` field.

Add Fields

Sometimes, we want to add additional fields to the query result without modifying the database schema. In ThinkPHP, you can use the model's `append` method to add fields to the result. Here’s how to add a field named `age` to the query results:

$users = User::select();
foreach ($users as $user) {
    $user->append(['age']);
    echo $user->name . ' - ' . $user->age;
}

In this code, `$user->append(['age'])` adds the `age` field to each user object in the query result. We then use `echo` to output both the `name` and `age` fields.

Conclusion

This article demonstrated how to query data and add extra fields using the `append` method in ThinkPHP. This approach allows developers to dynamically process and present query results, meeting various development needs.