lumen 分页_lumen 中实现分表
有一個(gè)日志表數(shù)據(jù)量很大,所以按每個(gè)月為單位生成一個(gè)表
一、根據(jù)月份創(chuàng)建新的數(shù)據(jù)表
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
// 獲取當(dāng)前的時(shí)間
$end = Carbon::now();
// 根據(jù)表名和年月拼接出新的表名
$table_name = 'h_login_store'.$end->format('Y_m');
// 檢查表是否存在數(shù)據(jù)庫(kù)中
if( Schema::hasTable($table_name) ){
echo '存在這個(gè)表';
}else{
echo '不存在這個(gè)表';
// 兩種方式創(chuàng)建數(shù)據(jù)表,任選一種:
// 1、根據(jù)已有的數(shù)據(jù)表直接復(fù)制
// 2、直接創(chuàng)建新的數(shù)據(jù)表
// 復(fù)制表,前提是h_login_store表在數(shù)據(jù)庫(kù)中存在
DB::update('create table '.$table_name.' like h_login_store');
// 創(chuàng)建表
Schema::create($table_name, function ($table) {
$table->increments('id');
$table->char('adname',45);
});
}
執(zhí)行后在數(shù)據(jù)庫(kù)中就會(huì)出現(xiàn)
image.png
二、分表后實(shí)現(xiàn)分頁(yè)、查詢
假設(shè)已經(jīng)運(yùn)行了很久了,有這么一些表
h_login_store_2020_03,h_login_store_2020_04,h_login_store_2020_05
怎么將這些表統(tǒng)一成一個(gè)表并進(jìn)行查詢、分頁(yè)
先循環(huán)查出時(shí)間段內(nèi)的表,并寫(xiě)入到查詢集合collect()中
把collect()中的表用unionAll組裝起來(lái)
再吧unionAll的聚合組裝成一個(gè)臨時(shí)表進(jìn)行查詢
// 開(kāi)始日期
$start = Carbon::parse('2020-02-01');
// 結(jié)束日期
$end = Carbon::now();
// 查詢集合
$queries = collect();
// 循環(huán)比較年月,添加每一張表的查詢
for ($i = $start->copy(); $i->format('Y-m') <= $end->format('Y-m'); $i->addMonth()) {
// 按日期循環(huán)組裝出表名
$tableName = "h_login_store{$i->format('Y_m')}";
// 檢查這個(gè)表是否存在
if( Schema::hasTable($tableName) ){
$queries->push(
DB::table($tableName)
// 建議都用select查詢字段,SQL盡可能的優(yōu)化性能
->select('store_code', 'store_name', 'password', 'store_id','created_at')
->where('store_code','=','234')
);
}
}
$unionQuery = $queries->shift();
// 循環(huán)剩下的表添加union
$queries->each(function ($item, $key) use ($unionQuery) {
$unionQuery->unionAll($item);
});
// 把用 unionAll鏈接起來(lái)的sql 組成一個(gè)表
$data = with(new SelectGoods)->setTable('h_login_store')
// 添加臨時(shí)表
->from(DB::raw("({$unionQuery->toSql()}) AS h_login_store"))
// 合并查詢條件
->mergeBindings($unionQuery)
// 按時(shí)間倒序
->orderBy('created_at', 'desc')
// 分頁(yè)
->paginate()
->toArray();
dd($data); //打印看看
image.png
總結(jié)
以上是生活随笔為你收集整理的lumen 分页_lumen 中实现分表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: u盘插入linux系统没有反应_linu
- 下一篇: td不允许自己扩展_一定要抱着大A不放手