Home php教程 php手册 ThinkPHP中的分表使用

ThinkPHP中的分表使用

Jun 07, 2016 am 11:35 AM

讲讲ThinkPHP中的分表使用
数据分表

对于大数据量的应用,经常会对数据进行分表,有些情况是可以利用数据库的分区功能,但并不是所有的数据库或者版本都支持,因此我们可以利用ThinkPHP内置的数据分表功能来实现。帮助我们更方便的进行数据的分表和读取操作。

和数据库分区功能不同,内置的数据分表功能需要根据分表规则手动创建相应的数据表。

在需要分表的模型中定义partition属性即可。

protected $partition = array(
'field' => 'name',// 要分表的字段 通常数据会根据某个字段的值按照规则进行分表
'type' => 'md5',// 分表的规则 包括id year mod md5 函数 和首字母
'expr' => 'name',// 分表辅助表达式 可选 配合不同的分表规则
'num' => 'name',// 分表的数目 可选 实际分表的数量
);
定义好了分表属性后,我们就可以来进行CURD操作了,唯一不同的是,获取当前的数据表不再使用getTableName方法,而是使用getPartitionTableName方法,而且必须传入当前的数据。然后根据数据分析应该实际操作哪个数据表。因此,分表的字段值必须存在于传入的数据中,否则会进行联合查询。

这是tp3.2.3官方文档介绍的,对于还未阅读tp源代码的coder,光看这几句话其实是很难理解如何在tp中使用分表技术的。之前我有专门了解过分表原理,再结合tp的源代码,我和分享一下我是怎么使用tp中的分表。
一、准备工作
1、安装最新的tp3.2.3框架 http://thinkphp.cn/down/framework.html
2、按自己的喜欢新建测试数据库(例如: thinkphp),接下来建表,因为我只需要完成功能演示就行,因此我就简单地建了tp_user、tp_blog_1、tp_blog_2。表结构如下:
表user:
id: 用户id, 自增,我们blog分表就是根据这个id去定位表的;
username: 账号

表tp_blog_1:
id: 博客id, 自增
uid: 作者用户 id
title: 标题
content: 内容

表tp_blog_2和表tp_blog_1一样
可以发现,我们是对blog表进行了分表操作,表的数量是2。
手动添加一些user表数据,演示要用到。

二、核心部分:建立模型
user表的模型和正常情况一样,这里不作说明。
重点在于blog表的模型,我直接先上BlogModel:<?php <br /> namespace Home\Model;<br> use Think\Model\AdvModel;<br> class BlogModel extends AdvModel{<br> <br>    protected $tableName = 'blog';<br>    Protected $autoCheckFields = false;  //一定要关闭字段缓存,不然会报找不到表的错误<br> <br>    protected $partition = array(<br>       'field' => 'uid',// 要分表的字段 通常数据会根据某个字段的值按照规则进行分表,我们这里按照用户的id进行分表<br>       'type' => 'mod',// 分表的规则 包括id year mod md5 函数 和首字母,此处选择mod(求余)的方式<br>       'expr' => '',// 分表辅助表达式 可选 配合不同的分表规则,这个参数没有深入研究<br>       'num' => '2',// 分表的数目 可选 实际分表的数量,在建表阶段就要确定好数量,后期不能增减表的数量<br>    );<br> <br>     /**<br>      * 计算在哪张表<br>      * @param array $data<br>      * @return \Think\Model<br>      */<br>    public function computeTable($data = []){<br>       $data = empty($data) ? $_POST : $data;<br>       $table = $this->getPartitionTableName($data);<br>       return $this->table($table);<br>    }这样我们的分表模型就可以工作了,接下来进行增删改查的演示操作。

三、演示
1、插入数据:
在BlogModel中新增函数addOne:/**<br>  * 添加一条数据<br>  * @param array $data<br>  * @return bool|int<br>  */<br> public function addOne($data=[]){<br>     if(empty($data[$this->partition['field']])){<br>         E('缺少' . $this->partition['field']);<br>     }<br>     $data['id'] = intval($this->computeTable()->max('id')) + 1;<br>     if($this->create($data)){<br>         $id = $this->computeTable($data)->add();<br>         if($id === false){<br>             $this->error = '插入数据错误';<br>             return false;<br>         }else{<br>             return $data['id'];<br>         }<br>     }<br>     return false;<br> } 在Home/Controller/IndexController文件新增操作addBlog:/**<br>  * 新增数据演示<br>  */<br> public function addBlog($uid=1){<br>     $blogM = D('Blog');<br>     for($i=1; $i          $this->show("<br>添加第{$i}条数据<br>");<br>         $data = ['title'=>'标题'.$i, 'content'=>'内容内容', 'uid'=>$uid];<br> <br>         $result = $blogM->addOne($data);<br>         if($result !== false){<br>             $this->show('插入数据后的id为:'.$result);<br>         }else{<br>             $this->show('插入数据失败,失败原因:'.$blogM->getError());<br>         }<br>     }<br> <br> }打开浏览器访问: 域名/index.php?s=/home/index/addBlog/uid/1 ,可以自行核对是否达到预期的效果。

2、获取所有博客:
在BlogModel中新增函数getAll:/**<br>  * 获取所有记录<br>  */<br> public function getAll(){<br> <br>     return $this->computeTable()->select();<br> }在Home/Controller/IndexController文件新增操作getBlogs:/**<br>  * 获取所有数据演示<br>  */<br> public function getBlogs(){<br>     $blogM = D('Blog');<br>     $list = $blogM->getAll();<br>     dump($list);<br> }浏览器访问: 域名/index.php?s=/home/index/getBlogs,可以自行核对是否达到预期的效果。

3、根据条件获取多条数据
在BlogModel中新增函数getList:/**<br>  * 条件查询列表<br>  * @param $map<br>  * @return mixed<br>  */<br> public function getList($map){<br>     if(empty($map[$this->partition['field']])){<br>         E('缺少' . $this->partition['field']);<br>     }<br> <br>     return $this->computeTable($map)->where($map)->select();<br> }在Home/Controller/IndexController文件新增操作getBlogByUid:/**<br>  * 根据条件查询数据演示<br>  * @param int $uid<br>  */<br> public function getBlogsByUid($uid = 1){<br>     $blogM = D('Blog');<br>     $list = $blogM->getList(['uid' => $uid]);<br>     dump($list);<br> }浏览器访问: 域名/index.php?s=/home/index/getBlogsByUid/uid/1,可以自行核对是否达到预期的效果。

4、查询单条记录
在BlogModel中新增函数getOne:/**<br>  * 根据查询条件获取一条记录<br>  * @param $map<br>  * @return mixed<br>  */<br> public function getOne($map){<br>     if(empty($map[$this->partition['field']])){<br>         E('缺少' . $this->partition['field']);<br>     }<br>     return $this->computeTable($map)->where($map)->find();<br> }在Home/Controller/IndexController文件新增操作blogDetail:/**<br>  * 查询一条数据演示<br>  * @param int $uid<br>  * @param int $blog_id<br>  */<br> public function blogDetail($uid = 1, $blog_id=1){<br>     $blogM = D('Blog');<br>     $data = $blogM->getOne(['uid' => $uid, 'id' => $blog_id]);<br>     dump($data);<br> }浏览器访问: 域名/index.php?s=/home/index/blogdetail/uid/1/blog_id/1,可以自行核对是否达到预期的效果。

5、更新一条记录
在BlogModel中新增函数updateOne:/**<br>  * 更新一条记录<br>  * @param $map<br>  * @param $data<br>  * @return bool<br>  */<br> public function updateOne($map, $data){<br>     if(empty($map[$this->partition['field']])){<br>         E('缺少' . $this->partition['field']);<br>     }<br>     if($this->create($data)){<br>         $res = $this->computeTable($map)->save($data);<br>         if($res === false){<br>             $this->error = '更新数据出错';<br>         }else{<br>             return $res;   //更新的数据条数<br>         }<br>     }<br>     return false;<br> }在Home/Controller/IndexController文件新增操作updateBlog:/**<br>  * 更新一条记录演示<br>  * @param int $uid<br>  * @param int $blog_id<br>  */<br> public function updateBlog($uid=1, $blog_id=1){<br>     $blogM = D('Blog');<br>     $map = ['uid'=>$uid, 'id'=>$blog_id];<br>     $this->show("id为".$blog_id."的博客在修改之前为<br>");<br>     $blog = $blogM->getOne($map);<br>     dump($blog);<br> <br>     $this->show("id为".$blog_id."的博客在修改之后为<br>");<br>     $data = ['title' => '我被修改了', 'id' => $blog_id];<br>     $res = $blogM->updateOne(['uid' => $uid], $data);<br>     if($res === false){<br>         dump($blogM->getError());<br>     }else{<br>         $blog = $blogM->getOne($map);<br>         dump($blog);<br>     }<br> }浏览器访问: 域名/index.php?s=/home/index/updateblog/uid/1/blog_id/1,可以自行核对是否达到预期的效果。

6、删除一条数据
在BlogModel中新增函数delOne:/**<br>  * 删除一条记录<br>  * @param $map<br>  * @return bool|mixed<br>  */<br> public function delOne($map){<br>     if(empty($map[$this->partition['field']])){<br>         E('缺少' . $this->partition['field']);<br>     }<br>     $res = $this->computeTable($map)->where($map)->delete();<br>     if($res === false){<br>         $this->error = '删除数据出错';<br>         return false;<br>     }else{<br>         return $res;   //删除数据个数<br>     }<br> }在Home/Controller/IndexController文件新增操作delBlog:/**<br>  * 删除一条数据演示<br>  * @param int $uid<br>  * @param int $blog_id<br>  */<br> public function delBlog($uid = 1, $blog_id=1){<br>     $blogM = D('Blog');<br>     $map = ['uid' => $uid, 'id' => $blog_id];<br>     $this->show("准备要删除的博客<br>");<br>     dump($blogM->getOne($map));<br> <br>     $this->show("删除结果<br>");<br>     $res = $blogM->delOne($map);<br>     dump($res);<br> }浏览器访问: 域名/index.php?s=/home/index/delblog/uid/1/blog_id/1,可以自行核对是否达到预期的效果。

以上只例举了一些其他操作,其他tp模型具有的操作可以举一反三得到,希望各自去使用。

AD:真正免费,域名+虚机+企业邮箱=0元

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
4 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)

Learn about introductory code examples for Python programming Learn about introductory code examples for Python programming Jan 04, 2024 am 10:50 AM

Learn about Python programming with introductory code examples Python is an easy-to-learn, yet powerful programming language. For beginners, it is very important to understand the introductory code examples of Python programming. This article will provide you with some concrete code examples to help you get started quickly. Print HelloWorldprint("HelloWorld") This is the simplest code example in Python. The print() function is used to output the specified content

PHP variables in action: 10 real-life examples of use PHP variables in action: 10 real-life examples of use Feb 19, 2024 pm 03:00 PM

PHP variables store values ​​during program runtime and are crucial for building dynamic and interactive WEB applications. This article takes an in-depth look at PHP variables and shows them in action with 10 real-life examples. 1. Store user input $username=$_POST["username"];$passWord=$_POST["password"]; This example extracts the username and password from the form submission and stores them in variables for further processing. 2. Set the configuration value $database_host="localhost";$database_username="username";$database_pa

From beginner to proficient: Code implementation of commonly used data structures in Go language From beginner to proficient: Code implementation of commonly used data structures in Go language Mar 04, 2024 pm 03:09 PM

Title: From Beginner to Mastery: Code Implementation of Commonly Used Data Structures in Go Language Data structures play a vital role in programming and are the basis of programming. In the Go language, there are many commonly used data structures, and mastering the implementation of these data structures is crucial to becoming a good programmer. This article will introduce the commonly used data structures in the Go language and give corresponding code examples to help readers from getting started to becoming proficient in these data structures. 1. Array Array is a basic data structure, a group of the same type

How to use PHP to write inventory management function code in the inventory management system How to use PHP to write inventory management function code in the inventory management system Aug 06, 2023 pm 04:49 PM

How to use PHP to write the inventory management function code in the inventory management system. Inventory management is an indispensable part of many enterprises. For companies with multiple warehouses, the inventory management function is particularly important. By properly managing and tracking inventory, companies can allocate inventory between different warehouses, optimize operating costs, and improve collaboration efficiency. This article will introduce how to use PHP to write code for inventory warehouse management functions, and provide you with relevant code examples. 1. Establish the database before starting to write the code for the inventory warehouse management function.

Java implements simple bubble sort code Java implements simple bubble sort code Jan 30, 2024 am 09:34 AM

The simplest code example of Java bubble sort Bubble sort is a common sorting algorithm. Its basic idea is to gradually adjust the sequence to be sorted into an ordered sequence through the comparison and exchange of adjacent elements. Here is a simple Java code example that demonstrates how to implement bubble sort: publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

Go language programming examples: code examples in web development Go language programming examples: code examples in web development Mar 04, 2024 pm 04:54 PM

"Go Language Programming Examples: Code Examples in Web Development" With the rapid development of the Internet, Web development has become an indispensable part of various industries. As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications. 1. Simple HTTP Server First, let’s start with a

Huawei Cloud Edge Computing Interconnection Guide: Java code examples to quickly implement interfaces Huawei Cloud Edge Computing Interconnection Guide: Java code examples to quickly implement interfaces Jul 05, 2023 pm 09:57 PM

Huawei Cloud Edge Computing Interconnection Guide: Java Code Samples to Quickly Implement Interfaces With the rapid development of IoT technology and the rise of edge computing, more and more enterprises are beginning to pay attention to the application of edge computing. Huawei Cloud provides edge computing services, providing enterprises with highly reliable computing resources and a convenient development environment, making edge computing applications easier to implement. This article will introduce how to quickly implement the Huawei Cloud edge computing interface through Java code. First, we need to prepare the development environment. Make sure you have the Java Development Kit installed (

Guidance and Examples: Learn to implement the selection sort algorithm in Java Guidance and Examples: Learn to implement the selection sort algorithm in Java Feb 18, 2024 am 10:52 AM

Java Selection Sorting Method Code Writing Guide and Examples Selection sorting is a simple and intuitive sorting algorithm. The idea is to select the smallest (or largest) element from the unsorted elements each time and exchange it until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code. Algorithm Principle The basic principle of selection sort is to divide the array to be sorted into two parts, sorted and unsorted. Each time, the smallest (or largest) element is selected from the unsorted part and placed at the end of the sorted part. Repeat the above

See all articles