如何在yii2中使用Create命令?

时间:2015-10-24 09:12:25

标签: mysqli yii2 yii2-advanced-app yii2-basic-app

我想创建一个新表,然后使用create命令将值插入其中。这是我试过的代码

if ( $model->save() )
            {
                $first_val      =   $model->num_start - 1;
                $connection     =   \Yii::$app()->db;
                $transaction    =   $connection->beginTransaction();
                try 
                {
                    $q =  "CREATE TABLE range_{$model->id}( id INT(11) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id) ); " ;      
                    $connection->createCommand($q)->execute(); // new table created
                    $transaction->commit();
                    if ( $model->num_start > 1 )
                    {
                        $r =  "INSERT INTO range_{$model->id}( id ) VALUES ({$first_val});" ;      
                        $connection->createCommand($r)->execute(); // new value inserted
                        $transaction->commit();
                    }

                } 
                catch (Exception $e) 
                {
                    // react on exception   
                    $transaction->rollback();
                } 

                return $this->redirect( [ 'index' ] );
}

当我尝试运行此代码时出现错误Call to undefined method Yii::app()如何在Yii2中使用create命令?

1 个答案:

答案 0 :(得分:1)

您混合了yiiyii2

使用:

\Yii::$app->db; 

而不是

\Yii::$app()->db;