Home PHP Framework Laravel Detailed explanation of query statements in thinkphp

Detailed explanation of query statements in thinkphp

Apr 21, 2023 am 10:10 AM

ThinkPHP is an open source PHP-based Web application framework that provides many tools and solutions for convenient development, including the construction and execution of query statements. This article will introduce the query statement function in ThinkPHP, including query builder and data model, to help developers perform database operations more efficiently.

1. Query Builder

ThinkPHP’s query builder is a set of object-oriented SQL statement builders that are used to quickly build complex SQL statements. In the query builder, you can build SQL statements of types SELECT, UPDATE, INSERT, and DELETE using several methods.

  1. SELECT query statement

Use the SELECT query statement to obtain data in the database. You can use the select() method of the query builder to build a SELECT query statement:

// 查询所有用户数据
Db::name('user')->select();

// 查询 id 为 1 的用户数据
Db::name('user')->where('id', 1)->find();

// 查询年龄大于 18 岁的用户数据
Db::name('user')->where('age', '>', 18)->select();
Copy after login

In the above code, Db::name('user') represents the data table to be queried. The select() method indicates querying all data; the find() method indicates querying a single record.

  1. UPDATE query statement

Use the UPDATE query statement to update data in the database. You can use the update() method of the query builder to build an UPDATE query statement:

// 更新 id 为 1 的用户数据
Db::name('user')->where('id', 1)->update(['name' => 'Tom']);

// 将所有用户的角色都更新为 2
Db::name('user')->update(['role_id' => 2]);
Copy after login

In the update() method, the first parameter represents the condition of the record to be updated, and the second parameter is the updated data. content.

  1. INSERT query statement

Use the INSERT query statement to insert new data into the database. You can use the insert() method of the query builder to build an INSERT query statement:

// 向 user 表中插入一条新数据
Db::name('user')->insert(['name' => 'Jack', 'age' => 20, 'role_id' => 1]);
Copy after login

In the insert() method, the parameter is the new data content to be inserted.

  1. DELETE query statement

Use the DELETE query statement to delete data in the database. You can use the delete() method of the query builder to build a DELETE query statement:

// 删除 id 为 1 的数据
Db::name('user')->where('id', 1)->delete();

// 删除所有角色为 3 的用户数据
Db::name('user')->where('role_id', 3)->delete();
Copy after login

In the delete() method, the parameter is the condition of the record to be deleted.

2. Data Model

In addition to the query builder, ThinkPHP also provides a set of database operation methods based on the data model, which can map the data table into a class, and can Automatically handle CRUD of database records based on changes in class attributes.

  1. Define the data model

You can use the following code to define a data model class:

namespace app\common\model;

use think\Model;

class User extends Model
{
    // 数据表名
    protected $table = 'user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 模型关联:用户角色
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }
}
Copy after login

In the above example, we inherit think\Model class defines a user data model class. The $table attribute indicates the name of the data table to be mapped, and the $autoWriteTimestamp attribute indicates whether to automatically write timestamps.

  1. Query data

We can use the find(), select(), where() and other methods of the data model to query the database:

// 查询 id 为 1 的用户数据
$user = User::find(1);

// 查询用户表中所有数据
$users = User::select();

// 查询年龄大于 18 岁的用户数据
$users = User::where('age', '>', 18)->select();
Copy after login

In the above example, we used the static methods of the data model class to perform database queries.

  1. Update and insert data

We can use the save() method of the data model to update and insert data:

// 更新 id 为 1 的用户数据
$user = User::find(1);
$user->name = 'Tom';
$user->save();

// 向 user 表中插入一条新数据
$user = new User;
$user->name = 'Jack';
$user->age = 20;
$user->role_id = 1;
$user->save();
Copy after login

In the above example , we use the properties of the data model object to set the data to be updated or inserted, and then call the save() method to submit it to the database.

  1. Delete data

We can use the delete() method of the data model to delete data:

// 删除 id 为 1 的用户数据
$user = User::find(1);
$user->delete();

// 删除所有角色为 3 的用户数据
User::where('role_id', 3)->delete();
Copy after login

In the above example, we used The delete() method of the data model object deletes the specified record. You can also use the where() method of the static method to select the record to be deleted, and then call the delete() method to delete it.

Summary

The above is how to use ThinkPHP to build query statements. The query builder provides a variety of methods to build SQL statements such as SELECT, UPDATE, INSERT and DELETE, and data models. It provides an object-oriented way to operate the database. Whether using the query builder or data model, we can quickly build complex SQL query statements to facilitate developers to perform database operations.

The above is the detailed content of Detailed explanation of query statements in thinkphp. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Build a RESTful API with Advanced Features in Laravel? How to Build a RESTful API with Advanced Features in Laravel? Mar 11, 2025 pm 04:13 PM

This article guides building robust Laravel RESTful APIs. It covers project setup, resource management, database interactions, serialization, authentication, authorization, testing, and crucial security best practices. Addressing scalability chall

Laravel framework installation latest method Laravel framework installation latest method Mar 06, 2025 pm 01:59 PM

This article provides a comprehensive guide to installing the latest Laravel framework using Composer. It details prerequisites, step-by-step instructions, troubleshooting common installation issues (PHP version, extensions, permissions), and minimu

laravel-admin menu management laravel-admin menu management Mar 06, 2025 pm 02:02 PM

This article guides Laravel-Admin users on menu management. It covers menu customization, best practices for large menus (categorization, modularization, search), and dynamic menu generation based on user roles and permissions using Laravel's author

What version of laravel is the best What version of laravel is the best Mar 06, 2025 pm 01:58 PM

This article guides Laravel developers in choosing the right version. It emphasizes the importance of selecting the latest Long Term Support (LTS) release for stability and security, while acknowledging that newer versions offer advanced features.

How to Implement OAuth2 Authentication and Authorization in Laravel? How to Implement OAuth2 Authentication and Authorization in Laravel? Mar 12, 2025 pm 05:56 PM

This article details implementing OAuth 2.0 authentication and authorization in Laravel. It covers using packages like league/oauth2-server or provider-specific solutions, emphasizing database setup, client registration, authorization server configu

What Are the Best Practices for Using Laravel in a Cloud-Native Environment? What Are the Best Practices for Using Laravel in a Cloud-Native Environment? Mar 14, 2025 pm 01:44 PM

The article discusses best practices for deploying Laravel in cloud-native environments, focusing on scalability, reliability, and security. Key issues include containerization, microservices, stateless design, and optimization strategies.

How can I create and use custom validation rules in Laravel? How can I create and use custom validation rules in Laravel? Mar 17, 2025 pm 02:38 PM

The article discusses creating and using custom validation rules in Laravel, offering steps to define and implement them. It highlights benefits like reusability and specificity, and provides methods to extend Laravel's validation system.

How do I create and use custom Blade directives in Laravel? How do I create and use custom Blade directives in Laravel? Mar 17, 2025 pm 02:50 PM

The article discusses creating and using custom Blade directives in Laravel to enhance templating. It covers defining directives, using them in templates, and managing them in large projects, highlighting benefits like improved code reusability and r

See all articles