繁体   English   中英

Yii2检查迁移中是否存在表

[英]Yii2 Check if table exists in migration

我创建了一个迁移,我应该为我的数据库创建表,并插入默认的admin用户。

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

}

当我运行此迁移时,我收到错误:

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

如果我包括use Yii我得到错误:

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

所以我似乎无法在迁移中使用Yii命名空间,如何检查表是否存在?

在迁移中,您可以通过以下方式检查表是否不存在:

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

它通常与以下相同:

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

是的,你可以在迁移中使用Yii ,如果你已经在全局命名空间中,那么从全局命名空间导入类是没有任何意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM