1. 程式人生 > >按日期建立資料庫表--美美美美菜菜菜菜

按日期建立資料庫表--美美美美菜菜菜菜

<?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; } }