Yii2 自动分表 model

其实是借鉴了一下某同学的《动态model》

redis;
        if($redis->sismember(static::$tableSetKey, $tableName))
            return $tableName;

        //if hit db
        $db = static::getDb();
        if($db->createCommand("SHOW TABLES LIKE '{$tableName}'")->queryAll()){
            $redis->sadd(static::$tableSetKey, $tableName);
            return $tableName;
        }else{ //maybe
            $redis->srem(static::$tableSetKey, $tableName);
        }

        //just do it
        $originalTable = static::$originalName;
        $createTableRet = $db->createCommand("SHOW CREATE TABLE `{$originalTable}`")->queryOne();
        $createTable = str_replace("`{$originalTable}`","`{$tableName}`",$createTableRet['Create Table']);
        $createTable = preg_replace('/\sAUTO_INCREMENT=\d+/','',$createTable);
        try{
            $db->createCommand($createTable)->execute();
            $redis->sadd(static::$tableSetKey, $tableName);
        }catch (Exception $ex){
            throw new Exception("Error execute sql: {$createTable}");
        }

        return $tableName;

    }

    /**
     * 扩展的find
     * @param $targetKey
     * @return \yii\db\ActiveQuery
     */
    public static function findx($targetKey = null){
        static::$tableName = static::renderTable($targetKey);
        return Yii::createObject(ActiveQuery::className(), [get_called_class(), ['from' => [static::tableName()]]]);
    }

    /**
     * 扩展的findAll
     * @param null $targetKey
     * @param array $params
     * @return \yii\db\ActiveQuery[]
     */
    public static function findAllx($targetKey = null,$params = []){
        return static::findByConditionx($targetKey, $params)->all();
    }

    /**
     * @Override
     * @param array $row
     * @return static
     */
    public static function instantiate($row){
        return new static(static::$targetKey);
    }

    /**
     * 禁止使用findBySql
     * @param string $sql
     */
    public static function findBySql($sql){
        throw new InvalidCallException("not allowed. {$sql}");
    }

    /**
     * 扩展的findOne
     * @param null $targetKey
     * @param array $condition
     * @return null|static|ActiveQuery
     */
    public static function findOnex($targetKey = null, $condition = []){
        return static::findByConditionx($targetKey, $condition)->one();
    }

    /**
     * 内部实现
     * @param null $targetKey
     * @param $condition
     * @return ActiveQuery[]|ActiveQuery
     * @throws InvalidConfigException
     */
    protected static function findByConditionx($targetKey = null, $condition){

        $query = static::findx($targetKey);

        if (!ArrayHelper::isAssociative($condition)) {
            // query by primary key
            $primaryKey = static::primaryKey();
            if (isset($primaryKey[0])) {
                $condition = [$primaryKey[0] => $condition];
            } else {
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
            }
        }

        return $query->andWhere($condition);
    }

}

分表model

where([]);
 * @use Test::findAllx($vip_card,[]);
 * @use Test::findOnex($vip_card,[]);
 *
 */

class Test extends Modelx
{
    //原始表名,表结构母版
    protected static $originalName = 'test';
    //redis表名set key
    protected static $tableSetKey = 'project:tableset';

    /**
     * 根据分表关键值获得表名
     * @Override
     * @return string
     */
    public static function getTableName(){
        return static::$originalName . '_'. (static::$targetKey % 10);
    }


}


分表使用原始表为模板进行结构复制,复制后的分表结构,不会同步原始表的结构、索引等改变。
建议在分表使用之前,对原始表做好充分优化。
分表之后的Model,不再支持findBySql方法。


你可能感兴趣的:(php)