按日期创建数据库表--美美美美菜菜菜菜

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值