namespace App\model;
use support\Db;
use support\Model;
class DemoModel extends Model
{
protected $table="demo";
public function __construct(array $attributes = [])
{
$data_table = $this->getTable();
$this->table = $data_table.date('Ym');
$result = Db::schema()->hasTable($this->table);
if (empty($result)) {
Db::update('create table ' . $this->table . ' like ' . $data_table);
}
parent::__construct($attributes);
}
}
namespace App\model;
use think\facade\Db;
use think\Model;
class DemoModel extends Model
{
protected $table="demo";
public function __construct(array $attributes = [])
{
$data_table = $this->getTable();
$this->table = $data_table.date('Ym');
$prefix = config('thinkorm.prefix')??'';
$result = Db::query("SHOW TABLES LIKE '{$prefix}{$this->table}'");
if (empty($result)) {
Db::query('create table ' . $this->table . ' like ' . $data_table);
}
parent::__construct($attributes);
}
}
/**
* 獲取分表數(shù)據(jù)
* @param string $table_name 原始表名
* @param array $where 條件
* @param int $page 分頁
* @param int $page_er 頁數(shù)數(shù)量
* @param array $select 表字段
* @param array $orderBy 排序
* @return mixed
*/
function getSubTableData(string $table_name = "", $where = [], int $page = 0, int $page_er = 10, array $orderBy = ['id'=>'desc'],$select = ['*'])
{
$offset = $page * $page_er;
// 開始日期
$start = Carbon::parse(date('Y-01-01'));
// 結(jié)束日期
$end = Carbon::now();
// 查詢集合
$queries = collect();
//把最原始表單的數(shù)據(jù)加入
if(Schema::hasTable($table_name)){
$queries->push(
DB::table($table_name)
// 建議都用select查詢字段,SQL盡可能的優(yōu)化性能
->select($select)
->where($where)
);
}
// 循環(huán)比較年月,添加每一張表的查詢
for ($i = $start->copy(); $i->format('Y-m') <= $end->format('Y-m'); $i->addMonth()) {
// 按日期循環(huán)組裝出表名
$tableName = $table_name . "_{$i->format('Ym')}";
// 檢查這個(gè)表是否存在
if (Schema::hasTable($tableName)) {
$queries->push(
DB::table($tableName)
// 建議都用select查詢字段,SQL盡可能的優(yōu)化性能
->select($select)
->where($where)
);
}
}
$unionQuery = $queries->shift();
// 循環(huán)剩下的表添加union
$queries->each(function ($item, $key) use ($unionQuery) {
$unionQuery->unionAll($item);
});
// 把用 unionAll鏈接起來的sql 組成一個(gè)表
$model = DB::table($table_name)
// 添加臨時(shí)表
->from(DB::raw("({$unionQuery->toSql()}) AS {$table_name}"))
// 合并查詢條件
->mergeBindings($unionQuery);
if ($orderBy) {
foreach ($orderBy as $k=>$v){
// 按時(shí)間倒序
$model->orderBy($k, $v);
}
}
$data['total'] = $model->count();
$data['data'] = $model->limit($page_er)->offset($offset)->get()->toArray();
return $data;
}
DML語句可能中斷事務(wù),在處理事務(wù)內(nèi)回滾等操作的時(shí)候會(huì)帶來麻煩;
個(gè)人建議為DML獨(dú)自創(chuàng)建定時(shí)器周期進(jìn)行建表操作,盡可能與DDL語句分離,保證事務(wù)執(zhí)行的純粹性
可以抽象一個(gè)Builder,這個(gè)Builder包含對應(yīng)的Model,包含對應(yīng)的定時(shí)進(jìn)程創(chuàng)建/移除相關(guān)的內(nèi)容(一般單進(jìn)程即可)。
比如實(shí)現(xiàn)一個(gè)command:webman:xxx-builder create acb --cron=' ',就可以創(chuàng)建一個(gè)名叫abc的Builder,并且把定時(shí)進(jìn)程加載到process.php中。
當(dāng)然這個(gè)方案也可以優(yōu)化,就是builder不與定時(shí)進(jìn)程一一對應(yīng),而是builder可以創(chuàng)建一個(gè)延時(shí)消息到消息隊(duì)列,消息隊(duì)列消費(fèi)者可以通過builder的建表方法執(zhí)行建表。
大概思路是這樣,因?yàn)橹霸谏a(chǎn)環(huán)境有遇到類似的,雖然不是php的項(xiàng)目,但思路差不多
不論是進(jìn)程還是線程,加載到配置文件這種方案都比較適合前期,因?yàn)殡S著服務(wù)實(shí)例部署的多了以后,管理是不方便的,通過服務(wù)注冊、調(diào)度系統(tǒng)、消息隊(duì)列這種方案更適合項(xiàng)目中后期,但進(jìn)程/線程+配置這個(gè)足夠用很長時(shí)間了。
我是這樣laravel orm分表的:
模型中設(shè)置靜態(tài)屬性$tableSuffix
然后模型中重寫getTable()方法
public function getTable(): string
{
return self::TABLE_NAME . '_' . self::$tableSuffix;
}
然后使用之前設(shè)置下表后綴
XXXModel::$tableSuffix='xxxxxxx';
然后每次訪問模型都要檢查下表是否存在,我感覺操作數(shù)據(jù)庫太頻繁了,所以我放到了文件中,先判斷文件是否存在,如果不存在,再判斷表是否存在。這樣查找文件比查找數(shù)據(jù)庫快一些。類似這樣
$tableName = 'xxxtable_' . $userId;
$filePath = 'user/' . $tableName;
if (!Storage::disk()->exists($filePath)) {
if (!Db::schema()->hasTable($tableName)) {
Db::statement("CREATE TABLE `$tableName` LIKE `xxxtables`;");
}
Storage::disk()->put($filePath, Carbon::now()->toDateTimeString());
}
// 設(shè)置表后綴
XXXModel::$tableSuffix = $userId;
可否發(fā)下thinkorm的呢