栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

laravel 8 实现 订单表按月份水平分表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

laravel 8 实现 订单表按月份水平分表

实现思路:

1.设计基础表orders

2.通过后台代码创建今年6月份订单表:order_202206,今年7月份订单表:order_202207...

创建表的时候需要进行判断,如果表存在,则不需要创建

这个后台代码会被多次使用并可以重复使用,选择写成trait

3.实现分表后的增删改查操作和分表前一样,但默认是对当前月份进行增删改查

trait:

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();
    }

    
    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();
    }

    
    public static function suffix($suffix = null)
    {
        $instance = new static;
        $instance->setSuffix($suffix);
        return $instance->newQuery();
    }

    
    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();
    }

效果:

按月分表适用场景:

按月分表作为分库分表的策略之一,可以做到冷热数据。

比如,本月的数据一般就是热数据,而之前月份的数据就是冷数据。

但是,应注意一件事情:如果本月写入数据很多,而上个月或者下个月数据写入很少,并且整个业务里根本不需要做一些月份数据的统计,就背离了因数据量多而进行分表的出发点,所以,分库分表应结合场景选用较为合适的策略,相比之下,取模适用场景比较广,可以较为均匀分担表数据。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/995990.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号