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