<?php class TOrderBaseModel extends DbModel { const BASE_TABLE_NAME = 't_order_base'; private static $db_connection; private static $thisMonthTableName = null; private static $_dateModels = null; private static $_createTable = []; private $dateTableName = null; public function tableName() { if(empty($this->dateTableName)) { $this->dateTableName = self::$thisMonthTableName; } return $this->dateTableName; } public static function model($create = false, $date = '', $className = __CLASS__) { //切换表时需要重新调用该方法 $model = self::getModelByDate($date); if($create && !in_array(self::$thisMonthTableName, self::$_createTable)) { Yii::app()->crm_data->createCommand("CREATE TABLE IF NOT EXISTS ".self::$thisMonthTableName." (LIKE ".self::BASE_TABLE_NAME.");")->execute(); self::$_createTable[] = self::$thisMonthTableName; } return $model; } public static function getModelByDate($date = '', $className = __CLASS__) { self::setTableNameByDate($date); $classNameByDate = $className.self::getTableSuffix($date); if(isset(self::$_dateModels[$classNameByDate])) { $model = self::$_dateModels[$classNameByDate]; } else { $model = self::$_dateModels[$classNameByDate]=new $className(null); $model->attachBehaviors($model->behaviors()); } //切换表时重置表名缓存 $model->refreshMetaData(); return $model; } public static function getDb() { if (empty(self::$db_connection)) { self::$db_connection = DBUtil::getDb(DBSource::CRM_DATA); } return self::$db_connection; } public function getDbConnection() { return self::getDb(); } public static function getTableSuffix($date = null) { if(empty($date)) { $time = time(); } else { $time = strtotime($date); } return date('Ym', $time); } public static function setTableNameByDate($date = null) { self::$thisMonthTableName = self::BASE_TABLE_NAME.self::getTableSuffix($date); return self::$thisMonthTableName; } }
按日期创建数据库表--美美美美菜菜菜菜
最新推荐文章于 2022-08-19 14:22:12 发布