TP5 Model function summary
TP5 provides powerful Model functions, follow this article to find out.
Introduction
tp5 model only performs business layer operations and does not perform specific link database SQL operations.
think\db\Connection.php does the link database operation
think\db\Builder.php does the create sql operation
think\db\Query.php does data CURD operations
Function list
Data automatic completion
Automatic writing of timestamp
Time field automatically formatted output field
Field validator
Auto-associated writing
Read-only field
Hidden field
Event callback
Soft delete
Type conversion
Function details
1. Data automatic completion
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
After setting the auto field in the model, when updating or adding, it will first determine whether the field set in auto exists. In the updated field ($this->change)
If it exists, the fields and values set in auto will not be used.
If it does not exist, the fields and values set in auto will be added to this->data and add the field to this->change.
If auto is an index array, that is, only the field name is set, and the subfield value is not set, the field value will be queried in $this->data according to the field name, and added to Go to the attribute array to be updated.
The method for adding new data is create, the method for modifying data is update, the method for batch adding and modifying is saveAll, the final implementation of these methods is to call the save method
The saveAll method adds and modifies in batches. It does not combine SQL statements, but starts a transaction, then calls the save method, adds and modifies one by one, and finally commits the transaction.
During the update operation, the model will automatically check whether the values of all fields in the data have been changed, and will only update the values of the changed fields. Anything that has not been changed is ignored.
The functions of insert and update are similar to the functions of auto, except that auto is used whether it is new data or updated data, while the insert value is for new additions, and update is only for updates. If the same attributes are set, insert and update will overwrite the fields in auto.
2. Automatically write timestamp
1 2 3 4 5 6 7 8 9 10 11 |
|
Configuration method
This configuration TP5 defaults to false and needs to be turned on manually
In the database configuration (database. php) to add global configuration.
1 2 3 |
|
Set in a separate model class
1 2 |
|
The field type of knowledge timestamp/datetime/int
If your data field is not the default value, you can set it in your own Modify in the model.
1 2 3 |
|
If you only need createTime but not updateTIme, you can turn off updateTIme in the model
1 2 |
|
Opening and closing in the model only works for a single model. Do you want it to work globally? To be configured in the configuration file.
3. Time field automatic formatting output
1 2 |
|
Configuration method
This configuration TP5 mode output format is 'Y-m-d H:i:s'
You can configure it yourself in the database configuration file (database.php). For example,
1 |
|
can also be set in the model
1 |
|
4. Field validator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Usage method
Configure field validation rules in the model, in New and update operations are common throughout the model.
// Advantages: You only need to set it once and it can be used universally
// Disadvantages: It cannot be set in a targeted manner
//For example: adding new users and editing user functions,
//New The password is added as a required item, and the password is optional when editing.
//So you cannot set the password verification rules in the model.
At this time, you can only set the password in the newly added action. Did the verification.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Call the think\Validate class during specific operations to implement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Comparison
Use the first method to set the verification rules in the model, although the structure looks comparable Reasonable, but this method is less flexible because it is judged when saving. If the save fails, you don't know whether the data validation failed or the data insertion failed. Therefore, it is very troublesome to do prompt verification (because we return the prompts for data verification directly to the user, but generally we do not return the prompts for database operations to the user, so we have to make judgments after getting the results, so it is more troublesome to verify them first).
使用第二种方法在action里定义一个_validate的函数,专门用来做数据校验,这中方法比较灵活,而且他是在在保存数据之前做的校验,所以返回结果分的比较清楚,对用户的提示也比较清晰,代码可读性也比较好。
5. 自动关联写入
1 2 3 |
|
暂时没有使用,后续再继续不补充。
6. 只读字段
1 2 3 4 5 |
|
7. 隐藏字段
1 2 3 4 5 |
|
当使用toArray和subToArray获得数组数据时,使用hidden字段和hidden函数可以隐藏数组中的元素。如:
1 2 |
|
在User模型中设置$hidden字段
1 2 3 4 5 6 7 8 |
|
8. 事件回调
支持的回调事件
before_insert 新增前
after_insert 新增后
before_update 更新前
after_update 更新后
before_write 写入前(新增和更新都会调用)
after_write 写入后(新增和更新都会调用)
before_delete 删除前
after_delete 删除后
注册的回调方法支持传入一个参数,当前示例模型对象,并且before_write,before_insert,before_update,before_delete返回false会结束执行。
使用方法
控制器里使用
1 2 3 4 5 6 7 8 |
|
模型里使用
1 2 3 4 5 6 7 8 9 10 11 12 |
|
原理
model类里有一个protected static $event = [];属性,注册的时间都存放在这个属性中。比如:
1 2 3 4 5 6 7 8 9 |
|
注册事件时,把所有的事件都保存在$event中了,然后在insert,update,delete等相应的位置调用即可。
9. 软删除
简介
在实际项目中,对数据频繁的使用删除操作可能会导致性能问题,软删除的作用就是给数据加上删除标记,而不是真正的删除,同时也便于需要的时候恢复数据。
设置方式
使用软删除功能需要引用SoftDelete trait;如:
1 2 3 4 5 6 7 8 9 10 11 |
|
dateteTIme属性用于标记数据表里的软删除字段,TP5里的软删除使用的是int类型,默认值为null(这个很重要,因为查询的时候是用delete_time is not null 来查询的),用于记录删除时间。
可以用类型转换指定软删除的字段类型,建议数据表里的所有时间字段使用同一种数据类型。
使用方式
在model中设置好后,就可以直接使用了
1 2 3 4 5 6 7 8 9 |
|
默认情况下,查询出来的数据是不包括软删除的数据的,如果想要查询包括软删除的数据,可以使用下面的方式。
1 2 |
|
如果仅需要查询软删除的数据,可以这样:
1 2 |
|
10. 类型转换
TP5支持给数据表中的字段设置类型,并会在读取和写入的时候自动转换。如:
1 2 3 4 5 6 7 8 |
|
使用示例
1 2 3 4 5 6 7 8 9 10 |
|
注意: 如果制定为时间戳类型(timestamp)的话,该字段会在写入的时候自动调用strtotime函数生成对应的时间戳,输出是自动使用dateFormat格式化时间戳,默认格式为Y:m:d H:i:s,如果想要改变输出格式,可以如下:
1 2 3 4 5 6 7 8 |
|
或者如下:
1 2 3 4 5 6 7 |
|
相关阅读:
The above is the detailed content of TP5 Model function summary. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.
