Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Check if table exists in migration

Tags:

php

yii2

I have created a migration, whichi should create tables for my database, and insert default admin user.

<?php

//use Yii;
use yii\db\Migration;
use yii\db\Schema;

/**
 * Class m180616_200856_create_tables
 */

require_once( __DIR__.'/../config.php');


class m180616_200856_create_tables extends Migration
{


    public function up()
    {

        if (Yii::$app->db->schema->getTable("users",true)===null) {
            $this->createTable('users', [
                'id' => $this->primaryKey(),
                'username' => $this->string(),
                'password' => $this->string(),
                'authKey' => $this->string(),
                'accessToken' => $this->string()
            ]);

            $this->insert('users',array(
                'username'=> SUPERUSER_LOGIN,
                'password' => md5(SUPERUSER_PASS ),
                'authKey' => 'key',
                'accessToken' => ''
            ));
        }
    }
    public function down()
    {
        echo "m180616_200856_create_tables cannot be reverted.\n";

        return false;
    }

}

When i run this migration, i get the error:

*** applying m180616_200856_create_tables
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\db\mysql\Schema::getTable()'

If i include use Yii i get the error:

*** applying m180616_200856_create_tables
PHP Warning 'yii\base\ErrorException' with message 'The use statement with non-compound name 'Yii' has no effect'

So it seems i cannot use Yii namespace inside migration, how can i check if table exists?

like image 812
KadirovRamZan Avatar asked Jun 16 '18 22:06

KadirovRamZan


1 Answers

In migration you can check if table does not exist in this way:

$tableName = $this->db->tablePrefix . 'users';
if ($this->db->getTableSchema($tableName, true) === null) {

It will usually work the same as:

$tableName = Yii::$app->db->tablePrefix . 'users';
if (Yii::$app->db->getTableSchema($tableName, true) === null) {

And yes, you can use Yii in migrations, it just does not make any sense to import class from global namespace if you're already in global namespace.

like image 105
rob006 Avatar answered Nov 18 '22 20:11

rob006