yii分表的一些分享

 public function checkTable($id = 1)
    {
        $table_name = 'te_' . $id;//你的表名
        $tableArr = Yii::$app->device->createCommand("show tables ")->queryAll();
        //判斷是否存在值是否存在二維數組中
        $arr = array_column($tableArr, 'Tables_in_shop');//shop 代表當前數據庫名
        if (!in_array($table_name, $arr)) {
            $this->createTable($tableName);
        }
        return $tableName;
    }
 /**
     * 創建表
     * @param type $tableName
     * @return type
     */
    private function createTable($tableName)
    {
        // 內部事務
        $transaction = Yii::$app->device->beginTransaction();
        try {
            $result = Yii::$app->device->createCommand("
                              CREATE TABLE `{$tableName}` (
                              `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                              `name`varchar(50) DEFAULT NULL ,
                              `age` int(3) DEFAULT NULL ,
                              `sex` int(2) DEFAULT NULLCOMMENT '性別' ,
                               `ip` varchar(11) DEFAULT NULL COMMENT '上次登錄Ip',
                              `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
                              `lasttime` int(11) DEFAULT NULL COMMENT '上次登錄時間時間',
                              PRIMARY KEY (`id`),
                              KEY `time` (`time`) USING BTREE
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='飛行日誌';
                       ")->execute();
            $transaction->commit();
        } catch (\Exception $e) {
            throw  $e;
            $transaction->rollBack();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章