【发布时间】: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 命名空间,如何检查表是否存在?
【问题讨论】: