search
HomePHP FrameworkThinkPHPThinkPHP: Correct use of Db classes and models

ThinkPHP: Correct use of Db classes and models

It is found that many developers do not understand the correct usage posture of Db and model when using ThinkPHP5.*, especially in version 5.1. If you do not use the following correct posture, there are It is very likely that you will step into a trap.

The correct posture of Db

The following is the officially recommended usage of the Db class (that is, static method calls every time)

// 查询单个数据
Db::name('user')->where('id', 1)->find();
// 查询多个数据
Db::name('user')->where('id', '>', 1)->select();
// 写入新的数据
Db::name('user')->insert(['name' => '张三']);
// 更新数据
Db::name('user')->where('id', 1)->update(['name' => '李四']);
// 删除数据
Db::name('user')->delete(1);

Many developers To simplify the code, readers like to use the following code.

However, never use the code below in 5.1!

// 错误的用法

$user = Db::name('user');
// 查询单个数据
$user->where('id', 1)->find();
// 查询多个数据
$user->where('id', '>', 1)->select();
// 写入新的数据
$user->insert(['name' => '张三']);
// 更新数据
$user->update(['name' => '李四']);
// 删除数据
$user->delete(1);

Even using the helper function is still not recommended!

// 仍然是错误的用法

// 查询单个数据
db('user')->where('id', 1)->find();
// 查询多个数据
db('user')->where('id', '>', 1)->select();
// 写入新的数据
db('user')->insert(['name' => '张三']);
// 更新数据
db('user')->update(['name' => '李四']);
// 删除数据
db('user')->delete(1);

Many developers may wonder why it is wrong usage? The results I used are obviously fine, right? This just means that you haven’t stepped into the trap yet.

The real reason is that version 5.1 will not clear the previous query conditions after each query (5.0 will clear them every time), so the following usage is valid.

$user = Db::name('user');
// 查询分数大于80分的用户总数
$count = $user->where('score', '>', 80)->count();
// 查询分数大于80分的用户数据
$user->select();

You should understand after seeing this that when you use the same database query object instance, the query conditions will always be retained (that is, it will cause subsequent query conditions to be confused), and if you Multiple operations using helper functions or manual instantiation will be the same object instance, unless you manually clear it as below.

$user = Db::name('user');
// 查询分数大于80分的用户总数
$count = $user->where('score', '>', 80)->count();
// 清除查询条件(但不包括排序或者字段等信息)
$user->removeOption('where');
// 查询所有用户数据 并按分数倒序排列 
$user->order('score', 'desc')->select();
// 清除所有查询条件
$user->removeOption();
// 查询分数等于100的用户
$user->where('score', 100)->select();

Best practice: Use a new Db static query every time

The correct posture of the model

The design of the model In fact, just like Db, there is basically no need to manually instantiate it.

// 写入新的数据
$user = User::create(['name' => '张三']);
// 更新数据
$user->update(['name' => '李四']);

// 查询单个数据
$user = User::get(1);
// 删除当前模型数据
$user->delete();

In the above code, we do not use any instantiation code, but use static method operations. The instantiation of the model is automatically completed by the system when querying or writing data. If you instantiate the model manually, it will cause the cost of repeated instantiation of the model.

Not recommended usage:

$user = new User;
// 写入新的数据
$user->name = '张三';
$user->save();
$user = new User;
$user->find(1);
echo $user->name;

Recommended usage:

// 写入新的数据
User::create(['name' => '张三']);
$user = User::get(1);
echo $user->name;

So, please do not instantiate the model manually, and it is not recommended to use the model helper function.

Best practice: use static methods for both model query and creation

Now, do you understand the correct posture for using Db classes and models?

PHP Chinese website has a large number of free ThinkPHP introductory tutorials, everyone is welcome to learn!

This article is reproduced from: https://blog.thinkphp.cn/810719

The above is the detailed content of ThinkPHP: Correct use of Db classes and models. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:ThinkPHP官网. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools