【问题标题】:Yii2 Check if table exists in migrationYii2 检查迁移中是否存在表
【发布时间】:2018-06-16 22:50:35
【问题描述】:

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

<?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 命名空间,如何检查表是否存在?

【问题讨论】:

    标签: php yii2


    【解决方案1】:

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

    $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,如果你已经在全局命名空间中,从全局命名空间导入类是没有任何意义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2019-06-08
      • 2023-04-10
      • 2021-10-28
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多