laravel 生成分表脚本示例

11 篇文章 0 订阅
8 篇文章 0 订阅

思路:
单表记录过大查询效率低下,可以考虑将表分为月度,年度的表来存数据。

建表脚本: (以下只是示例,按实际需求调整)

<?php

namespace App\Console\Commands\Table;

use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class TableCopy extends Command
{
    protected $signature = 'cron:table-copy {table?}';

    protected $table_date_format = 'Y';

    public function handle()
    {
        $table_base = $this->argument('table') ?: 'promotion_water';
        try {
            switch($table_base) {
                case 'promotion_water':
                    $table_name = $table_base.'_'.date($this->table_date_format);
                    $rt = $this->check_promotion_running_water_table($table_name);
//            $rt && $this->info('created table success! table:'.$table_name);
                    $rt && logger('created table success! table:'.$table_name);
                    break ;
                default:
                    break ;
            }
        } catch (\Exception $e) {
            logger('TableCreate.error',['table_base'=> $table_base,$e->getMessage()]);
        }
    }

    public function check_promotion_running_water_table($table_name)
    {
        if(!Schema::hasTable($table_name)) {
            Schema::create($table_name, function (Blueprint $table) {
                $table->increments('id');
                $table->string('serial_number')->index()->comment('流水号');
                $table->string('seller_id')->index()->comment('渠道号');
                $table->string('userno')->index()->comment('推广者ID');
                $table->string('cardId')->index()->comment('卡ID');
                $table->string('proCode')->index()->comment('来源码');
                $table->string('link')->index()->comment('落地页链接');
                $table->string('from')->index()->comment('来源');
                $table->string('ip')->index()->comment('IP');
                $table->datetime('time')->index()->comment('');
                $table->timestamps();
            });
            if(Schema::hasTable($table_name)) {
                return true;
            }
        }
        return false;
    }
}

定时任务配置

 //app/Console/Kernel.php
 $schedule->command('cron:table-copy')->dailyAt('00:00')->runInBackground();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值