Home > PHP Framework > ThinkPHP > what is orm in thinkphp

what is orm in thinkphp

青灯夜游
Release: 2022-02-14 17:04:06
Original
4280 people have browsed it

In thinkphp, ORM refers to "object relational mapping", which is a storage access layer to facilitate developers to use database development; the main purpose of ORM is to map objects represented by the object model to SQL-based relational model database structure.

what is orm in thinkphp

The operating environment of this tutorial: Windows 7 system, thinkphp v5.1 version, Dell G3 computer.

orm in thinkphp

The full name of ORM is Object Relational Mapping, that is, object relational mapping

  • O (Object) Object is the entity in the project. To be more precise, it is the data Model, which can also be said to be the persistence class.

  • R (Relation) Relational data

  • M (Mapping) mapping, mapping objects to relational data, mapping relational data to objects process.

A more intuitive understanding is that ORM uses OOP thinking to generate add, delete, modify and query SQL statements.

ThinkPHP's ORM is a storage access layer for developers to use database development. The framework design picture is as follows:

what is orm in thinkphp

The main purpose is: to convert the object model The represented objects are mapped to the SQL-based relational model database structure.

When changing the properties of the object itself or calling the method of the object, the corresponding execution of certain SQL statements is.

In this way, people who write code can better write business logic instead of repeatedly writing add, delete, modify and query SQL statements.

Application examples in thinkphp

There are two modules for database operations in the TP framework:

  • Database

  • Model

Database module in tp

Quote the characteristics of a document Description

Split into Connection/Query/Builder(SQL generator)

  • Connection connector main It is used to connect to the database. You can use different drivers to connect to different types of databases.

  • Query query is used to run sql statements, process the results, and map them to the data set.

  • The Builder generator is used to convert the conditions, sorting, etc. we pass in into SQL statements.

In these 3 steps, we can know that if there is an abstract mapping of ORM ideas used, it can only be the Query query module, but we can carefully check the TP document Description of the data set.

It is more about encapsulating and providing data processing methods, such as:

(The following is a small part copied from the document)

toArray     将数据集的数据转为数组
merge   合并其它数据
diff    比较数组,返回差集
flip    交换数据中的键和值
intersect   比较数组,返回交集
keys    返回数据中的所有键名
pop 删除数据中的最后一个元素
shift   删除数据中的第一个元素
unshift 在数据开头插入一个元素
reduce  通过使用用户自定义函数,以字符串返回数组
Copy after login

But it is not provided Reverse mapping relational operations, such as when we operate a data set, automatically update the data in the database.

So in my understanding, there are not many ORM ideas in the database module. The focus is still on understanding and applying the model

The model in tp

Define model file

namespace app\index\model;

use think\Model;

// 设置类名 需要遵循转换规则,蛇形转为大驼峰
class User extends Model
{
    // 设置主键字段名
    protected $pk = 'u_id';

    // 开启自动维护时间戳字段 (什么时间插入 什么时间更新)
    protected $autoWriteTimestamp = true;

    // 软删除 开启之后 删除数据只是用一个字段来标识为删除状态 方便查询、备份等
    use SoftDelete;
    protected $deleteTime = 'delete_time';

}
Copy after login

The above code has more content than the model initialization in the first chapter of the document. This is to highlight that the model can complete many functions

This is also the reason for the emergence of ORM : Abstractly map the execution of SQL to objects in object-oriented programming.

We can understand it as: a row of data in the table represents a new object in our code. If the object is changed, the corresponding row in the table will be automatically updated.

Using the model

The code demonstrated is relatively simple, but in reality it can be very flexible

For example, the query uses non-primary key conditions to query, Querying multi-line records, etc.

<?php
// *******快速查询、更新*******
// 查询主键=1的数据
$user = User::get(1);
// 然后更改它的name字段为新的值
$user->name = &#39;thinkphp&#39;;
// 保存,自己去数据库给我更新吧~
$user->save();

// *******插入新的一行数据*******
// 新建一个对象(相对应的操作就是新创建一行)
$user = new User;
// 设置字段的值  有多个字段就多个设置
$user->name= &#39;thinkphp&#39;;
// 保存,自己去插入吧~
$user->save();
Copy after login

Misunderstanding

After seeing how to use it, many beginners start to write code, but they use incorrect methods.

① The model should only be used for the Db class

Although the model can be regarded as a superset of the db class, if you just use it as a simple DB class, rather than using ORM ideas to write it . Then there is no need to use it. .

If you use it incorrectly, it will not only fail to improve efficiency, but will affect yourself. (For example, code specifications are not unified, new tables need to be added with corresponding model files, etc.)

Code demonstration:

<?php
$userModel = new User(); // 这里就相当于初始化Db类
$userOneInfo = $userModel->where([&#39;u_id&#39; => 1])->find();

$userTwoInfo = $userModel->where([&#39;u_id&#39; => 2])->find();
// ... 执行其他逻辑 比如判断上下级 操作权限等等

// 业务需求不只是读取用户的数据这么简单
// 还要扣除余额(就是更新数据库)
$userOneRes = $userModel->where([&#39;u_id&#39; => 1])->update([&#39;u_balance&#39; => &#39;xxxx&#39;]);

// ... 执行其他逻辑
Copy after login

When you see this, stop and think about it. . Has your code ever looked like this?

I believe some people still use it like this! Because I used to use it this way.

Then let’s take a look at the correct way to use it (in my opinion, if you think it’s wrong or have a better one, please comment and exchange)

<?php

$userOneInfo = User::get(1);

// 这里演示使用非主键条件查询的情况!!
// 查询一个1用户的下级出来
$userTwoInfo = User::get(function($query){
    $query->where([&#39;p_uid&#39; => 1]);
});

// ... 执行其他逻辑 比如判断上下级 操作权限等等

// 业务需求不只是读取用户的数据这么简单
// 还要扣除余额(就是更新数据库)
$userOneInfo->u_balance = 0;
$userOneRes = $userOneInfo->save();

$userTwoInfo->u_balance = 0;
$userTwoRes =  $userTwoInfo->save();

// ... 执行其他逻辑
Copy after login

Because an object maps a piece of data, we are operating For data with the same where condition, just operate the object directly. There is no need to repeatedly write where u_id =1 update, u_id = 1 to delete the

usage model, there are many uses, (thanks to the dedication of the open source team, which encapsulates a large number of functions for us)

for example:

– When a new piece of data is added to the user table, another subsidiary table must also initialize a row with the user ID.

– Automatically convert the data format (save the timestamp, and the query will be in 2019-7-13 19:53:04 format).

– Automatically verify data and automatically complete data (the operator’s IP permissions, etc. are stored by default during operation).

– Related query (a very powerful function in TP. The relationship with another model is defined in the model. For example, the u_id in the store table can be used to query the information of the user who belongs to the store. It is equivalent to the store model and Association of user model Automatically join data merge and return to us)

– etc.

Summary

ORM is a An idea and concept that represents object-relational mapping (database-object mapping) ORM abstracts operations on data into operations on objects. Learn to change your thinking, make good use of the features provided by the framework, and write better code. The model in TP is very powerful and encapsulates a lot of logic.

[Related tutorial recommendations: thinkphp framework]

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template