当前位置:网站首页>laravel 8 实现 订单表按月份水平分表
laravel 8 实现 订单表按月份水平分表
2022-06-29 08:17:00 【amateur12】
实现思路:
1.设计基础表orders
2.通过后台代码创建今年6月份订单表:order_202206,今年7月份订单表:order_202207...
创建表的时候需要进行判断,如果表存在,则不需要创建
这个后台代码会被多次使用并可以重复使用,选择写成trait
3.实现分表后的增删改查操作和分表前一样,但默认是对当前月份进行增删改查
trait:
<?php
namespace App\Traits;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
trait OrderTraits
{
//是否分表,默认false,即不分表
protected $isSplitTable = true;
//原表
public $originTable;
//表
public $endTable;
/**
* 后缀参数
* @var string
*/
protected $suffix = null;
/**
* 年月参数:202104
* @var string
*/
public $ym;
public function init(array $attributes = [], $suffix = null)
{
//默认原表
$this->originTable = $this->table;
//默认最终表
$this->endTable = $this->table;
$this->ym = Carbon::now()->format('Ym');
//isSplitTable参数为true时进行分表,否则不分表
if ($this->isSplitTable) {
//初始化后缀,未传则默认年月分表
$this->suffix = $suffix ?: $this->ym;
}
//初始化分表表名并创建
$this->setSuffix();
}
/**
* 设置表后缀, 如果设置分表后缀,可在service层调用生成自定义后缀表名,
* 但每次操作表之前都需要调用该方法以保证数据表的准确性
* @param $suffix
*/
public function setSuffix($suffix = null)
{
//isSplitTable参数为true时进行分表,否则不分表
if ($this->isSplitTable) {
//初始化后缀,未传则默认年月分表
$this->suffix = $suffix ?: $this->ym;
}
if ($this->suffix !== null) {
//$this->endTable = $this->getTable() . '_' . $suffix;
$this->endTable = $this->originTable . '_' . $this->suffix;
//最终表替换模型中声明的表作为分表使用的表
$this->table = $this->endTable;
}
//调用时,创建分表,格式为 table_{$suffix}
//未传自定义后缀情况下,,默认按年月分表格式为:orders_202205
//无论使用时是否自定义分表名,都会创建默认的分表,除非关闭该调用
$this->createTable();
}
/**
* 提供一个静态方法设置表后缀
* @param string $suffix
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function suffix($suffix = null)
{
$instance = new static;
$instance->setSuffix($suffix);
return $instance->newQuery();
}
/**
* 创建新的"table_{$suffix}"的模型实例并返回
* @param array $attributes
* @param bool $exists
* @return object $model
*/
public function newInstance($attributes = [], $exists = false)
{
$model = parent::newInstance($attributes, $exists);
$model->setSuffix($this->suffix);
return $model;
}
/**
* 创建分表,没有则创建,有则不处理
*/
protected function createTable()
{
info("createTable===============", [Schema::hasTable($this->endTable)]);
//初始化分表,,按年月分表格式为:orders_202205
if (!Schema::hasTable($this->endTable)) {
info("创建表==========", [$this->endTable]);
DB::update("create table {$this->endTable} like {$this->originTable}");
}
}
}
在order模型使用trait:(任何模型都可使用这个trait进行按月分表)
use OrderTraits;
protected $table = "orders";
protected $primaryKey = 'id';
protected $guarded = [];
protected $columns;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// 初始化分表处理
$this->init();
}效果:

按月分表适用场景:
按月分表作为分库分表的策略之一,可以做到冷热数据。
比如,本月的数据一般就是热数据,而之前月份的数据就是冷数据。
但是,应注意一件事情:如果本月写入数据很多,而上个月或者下个月数据写入很少,并且整个业务里根本不需要做一些月份数据的统计,就背离了因数据量多而进行分表的出发点,所以,分库分表应结合场景选用较为合适的策略,相比之下,取模适用场景比较广,可以较为均匀分担表数据。
边栏推荐
- 人民链鲍大伟:打破壁垒,建立全域数据治理共享及应用平台
- MQTT第二话 -- emqx高可用集群实现
- Compare homekit, MI family, and zhiting family cloud edition for what scene based experiences
- Np5 formatted output (III)
- Oracle subquery
- sed 替换值为变量
- 闭关修炼(二十一)Servlet生命周期、service方法源码分析、线程安全问题
- “国防七校”之一西工大遭境外网络攻击
- Voice processing tool: Sox
- Some "non-technical" Thoughts on distributed digital identity
猜你喜欢

航芯开发板&调试器

对话| 数字时代,隐私计算的发展前景与挑战
![[microservices openfeign] timeout of openfeign](/img/b1/9bc92250b4d544c704d2af5c08d059.png)
[microservices openfeign] timeout of openfeign

The final of the sixth season of 2022 perfect children's model Hefei division came to a successful conclusion

城通网盘仿蓝奏网盘源码 附带视频教程

壁纸小程序源码双端微信抖音小程序
![Target tracking [single target tracking (vot/sot), target detection, pedestrian re identification (re ID)]](/img/f2/d42032f05214a4ad9339ea18966cc2.jpg)
Target tracking [single target tracking (vot/sot), target detection, pedestrian re identification (re ID)]

Typescript variable declaration - type assertion

Baodawei of the people's Chain: break down barriers and establish a global data governance sharing and application platform

sql server 用 administrator 权限运行吗?还是以普通用户运行呢?
随机推荐
Debugging nocturnal simulator with ADB command
Sorting out easily confused words in postgraduate entrance examination English 【 flash 】
2022第六季完美童模 海口赛区 选拔赛圆满落幕
Transformer details
The final of the sixth season of 2022 perfect children's model Hefei division came to a successful conclusion
Np5 formatted output (III)
Operating system product key viewing method
操作系统产品密钥查看方法
今天让你知道PMP考试通过率达97%,可信不可信
C# 语音端点检测(VAD)实现过程分析
Speech signal processing - Fundamentals (I): basic acoustic knowledge
工作好多年,回忆人生--高中三年
Is it really safe to open a stock account online? Find the answer
Batch processing of experimental contact angle data matlab analysis
Paddlenlp general information extraction model: UIE [information extraction {entity relationship extraction, Chinese word segmentation, accurate entity markers, emotion analysis, etc.}, text error cor
TypeScript 變量聲明 —— 類型斷言
(pytorch进阶之路三)encoder self attention mask
TypeScript 变量声明 —— 类型断言
Résumé des différentes séries (harmoniques, géométriques)
P4769-[NOI2018]冒泡排序【组合数学,树状数组】