クラス yii\console\controllers\MigrateController
アプリケーションのマイグレーションを管理します。
マイグレーションとは、異なる開発者間で共有されるアプリケーション環境への永続的な変更のセットを意味します。例えば、データベースによって支えられたアプリケーションでは、マイグレーションは、新しいテーブルの作成や新しいテーブル列の追加など、データベースへの一連の変更を指す場合があります。
このコマンドは、マイグレーション履歴の追跡、マイグレーションを使用したアップグレードまたはダウンロード、および新しいマイグレーションスケルトンの作成をサポートします。
マイグレーション履歴は、$migrationTable という名前のデータベーステーブルに保存されます。テーブルが存在しない場合、このコマンドが最初に実行されるときに自動的に作成されます。また、次のように手動で作成することもできます。
CREATE TABLE migration (
version varchar(180) PRIMARY KEY,
apply_time integer
)
以下は、このコマンドの一般的な使用方法です。
# creates a new migration named 'create_user_table'
yii migrate/create create_user_table
# applies ALL new migrations
yii migrate
# reverts the last applied migration
yii migrate/down
2.0.10 以降、名前空間付きのマイグレーションを使用できます。この機能を有効にするには、アプリケーション構成でコントローラの $migrationNamespaces プロパティを設定する必要があります。
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations',
'some\extension\migrations',
],
//'migrationPath' => null, // allows to disable not namespaced migration completely
],
],
];
公開プロパティ
パブリックメソッド
保護されたメソッド
イベント
イベント | 型 | 説明 | 定義元 |
---|---|---|---|
EVENT_AFTER_ACTION | yii\base\ActionEvent | コントローラーアクションの実行直後に発生するイベント。 | yii\base\Controller |
EVENT_BEFORE_ACTION | yii\base\ActionEvent | コントローラーアクションの実行直前に発生するイベント。 | yii\base\Controller |
定数
定数 | 値 | 説明 | 定義元 |
---|---|---|---|
BASE_MIGRATION | 'm000000_000000_base' | マイグレーション履歴全体の開始を示すダミーマイグレーションの名前。 | yii\console\controllers\BaseMigrateController |
EXIT_CODE_ERROR | 1 | 2.0.13以降非推奨。代わりにyii\console\ExitCode::UNSPECIFIED_ERRORを使用してください。 | yii\console\Controller |
EXIT_CODE_NORMAL | 0 | 2.0.13以降非推奨。代わりにyii\console\ExitCode::OKを使用してください。 | yii\console\Controller |
MAX_NAME_LENGTH | 180 | マイグレーション名の最大長。 | yii\console\controllers\MigrateController |
プロパティの詳細
マイグレーションを適用するときに使用するDB接続オブジェクトまたはDB接続のアプリケーションコンポーネントID。バージョン2.0.3以降では、オブジェクトを作成するための構成配列にすることもできます。
マイグレーションコードの作成に使用する列定義文字列。
各定義のフォーマットは、COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR
です。区切り文字は ,
です。例えば、--fields="name:string(12):notNull:unique"
は、null でなく、かつ一意の値であるサイズ 12 の文字列カラムを生成します。
注意:プライマリキーは自動的に追加され、デフォルトでは id という名前が付けられます。別の名前を使用したい場合は、--fields="id_key:primaryKey,name:string(12):notNull:unique"
のように明示的に指定できます。
マイグレーションコードを自動的に生成するためのテンプレートパスのセット。
キーはテンプレートタイプ、値はパスまたはエイリアスです。サポートされているタイプは次のとおりです。
create_table
:テーブル作成テンプレートdrop_table
:テーブル削除テンプレートadd_column
:新しいカラム追加テンプレートdrop_column
:カラム削除テンプレートcreate_junction
:ジャンクション作成テンプレート
'create_table' => '@yii/views/createTableMigration.php',
'drop_table' => '@yii/views/dropTableMigration.php',
'add_column' => '@yii/views/addColumnMigration.php',
'drop_column' => '@yii/views/dropColumnMigration.php',
'create_junction' => '@yii/views/createTableMigration.php',
]
適用されたマイグレーション情報を保持するためのテーブルの名前。
新しいマイグレーションを生成するためのテンプレートファイル。これは、パスエイリアス (例: "@app/migrations/template.php") またはファイルパスのいずれかです。
生成されるテーブル名が、DB接続の tablePrefix
設定を考慮するかどうかを示します。たとえば、テーブル名が post
の場合、ジェネレーターは {{%post}}
を返します。
メソッド詳細
定義元: yii\base\Component::__call()
クラスメソッドではない指定されたメソッドを呼び出します。
このメソッドは、アタッチされたビヘイビアに名前付きメソッドがあるかどうかを確認し、利用可能であれば実行します。
不明なメソッドが呼び出されたときに暗黙的に呼び出されるPHPマジックメソッドであるため、このメソッドを直接呼び出さないでください。
public mixed __call ( $name, $params ) | ||
$name | string |
メソッド名 |
$params | array |
メソッドのパラメータ |
return | mixed |
メソッドの戻り値 |
---|---|---|
throws | yii\base\UnknownMethodException |
不明なメソッドを呼び出すとき |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
定義元: yii\base\Component::__clone()
このメソッドは既存のオブジェクトをクローンすることで作成された後に呼び出されます。
古いオブジェクトにアタッチされているため、すべてのビヘイビアを削除します。
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
public void __construct ( $id, $module, $config = [] ) | ||
$id | string |
このコントローラの ID。 |
$module | yii\base\Module |
このコントローラが属するモジュール。 |
$config | array |
オブジェクトのプロパティを初期化するために使用される名前と値のペア。 |
public function __construct($id, $module, $config = [])
{
$this->id = $id;
$this->module = $module;
parent::__construct($config);
}
定義元: yii\base\Component::__get()
コンポーネントプロパティの値を返します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- ゲッターで定義されたプロパティ:ゲッターの結果を返す
- ビヘイビアのプロパティ:ビヘイビアのプロパティ値を返す
$value = $component->property;
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、このメソッドを直接呼び出さないでください。
参照 __set()。
public mixed __get ( $name ) | ||
$name | string |
プロパティ名 |
return | mixed |
プロパティ値またはビヘイビアのプロパティの値 |
---|---|---|
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
throws | yii\base\InvalidCallException |
プロパティが書き込み専用の場合。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
定義元: yii\base\Component::__isset()
プロパティが設定されているかどうか、つまり定義されていてNULLでないかどうかを確認します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターで定義されたプロパティ:プロパティが設定されているかどうかを返す
- ビヘイビアのプロパティ:プロパティが設定されているかどうかを返す
- 存在しないプロパティの場合は
false
を返す
isset($component->property)
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、このメソッドを直接呼び出さないでください。
public boolean __isset ( $name ) | ||
$name | string |
プロパティ名またはイベント名 |
return | boolean |
名前付きプロパティが設定されているかどうか |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
定義元: yii\base\Component::__set()
コンポーネントプロパティの値を設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターによって定義されたプロパティ:プロパティ値を設定します。
- "on xyz" という形式のイベント:"xyz" イベントにハンドラをアタッチします。
- "as xyz" という形式のビヘイビア:"xyz" という名前のビヘイビアをアタッチします。
- ビヘイビアのプロパティ:ビヘイビアのプロパティ値を設定します。
このメソッドは、`$component->property = $value;` を実行したときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
__get() も参照してください。__get()。
public void __set ( $name, $value ) | ||
$name | string |
プロパティ名またはイベント名 |
$value | mixed |
プロパティ値 |
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
---|---|---|
throws | yii\base\InvalidCallException |
プロパティが読み取り専用の場合。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
定義元: yii\base\Component::__unset()
コンポーネントプロパティをNULLに設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターによって定義されたプロパティ:プロパティ値を null に設定します。
- ビヘイビアのプロパティ:プロパティ値を null に設定します。
このメソッドは、`unset($component->property)` を実行したときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
public void __unset ( $name ) | ||
$name | string |
プロパティ名 |
throws | yii\base\InvalidCallException |
プロパティが読み取り専用の場合。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
定義元: yii\console\controllers\BaseMigrateController::actionCreate()
新しいマイグレーションを作成します。
このコマンドは、利用可能なマイグレーションテンプレートを使用して新しいマイグレーションを作成します。このコマンドを使用した後、開発者は作成されたマイグレーションのスケルトンを修正して、実際のマイグレーションロジックを記述する必要があります。
yii migrate/create create_user_table
名前空間付きのマイグレーションを生成するには、マイグレーションの名前の前に名前空間を指定する必要があります。バックスラッシュ (\
) は通常シェルで特別な文字と見なされるため、シェルエラーや不正な動作を避けるために適切にエスケープする必要があることに注意してください。例えば
yii migrate/create app\\migrations\\createUserTable
$migrationPath が設定されておらず、名前空間が指定されていない場合、$migrationNamespaces の最初のエントリが使用されます。
public void actionCreate ( $name ) | ||
$name | string |
新しいマイグレーションの名前。文字、数字、アンダースコア、および/またはバックスラッシュのみを含める必要があります。 注:マイグレーション名が、create_xxx や drop_xxx など、特別な形式の場合、生成されたマイグレーションファイルには追加のコード(この場合はテーブルの作成/削除用)が含まれます。 |
throws | yii\console\Exception |
name 引数が無効な場合。 |
---|
public function actionCreate($name)
{
if (!preg_match('/^[\w\\\\]+$/', $name)) {
throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
}
list($namespace, $className) = $this->generateClassName($name);
// Abort if name is too long
$nameLimit = $this->getMigrationNameLimit();
if ($nameLimit !== null && strlen($className) > $nameLimit) {
throw new Exception('The migration name is too long.');
}
$migrationPath = $this->findMigrationPath($namespace);
$file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
if ($this->confirm("Create new migration '$file'?")) {
$content = $this->generateMigrationSourceCode([
'name' => $name,
'className' => $className,
'namespace' => $namespace,
]);
FileHelper::createDirectory($migrationPath);
if (file_put_contents($file, $content, LOCK_EX) === false) {
$this->stdout("Failed to create new migration.\n", Console::FG_RED);
return ExitCode::IOERR;
}
FileHelper::changeOwnership($file, $this->newFileOwnership, $this->newFileMode);
$this->stdout("New migration created successfully.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::actionDown()
古いマイグレーションを元に戻すことでアプリケーションをダウングレードします。
例えば、
yii migrate/down # revert the last migration
yii migrate/down 3 # revert the last 3 migrations
yii migrate/down all # revert all migrations
public integer actionDown ( $limit = 1 ) | ||
$limit | integer|string |
ロールバックするマイグレーションの数。デフォルトは 1 で、最後に適用されたマイグレーションがロールバックされることを意味します。値が "all" の場合、すべてのマイグレーションがロールバックされます。 |
return | integer |
アクション実行の状態。0 は正常、それ以外の値は異常を意味します。 |
---|---|---|
throws | yii\console\Exception |
指定されたステップ数が 1 未満の場合。 |
public function actionDown($limit = 1)
{
if ($limit === 'all') {
$limit = null;
} else {
$limit = (int) $limit;
if ($limit < 1) {
throw new Exception('The step argument must be greater than 0.');
}
}
$migrations = $this->getMigrationHistory($limit);
if (empty($migrations)) {
$this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
return ExitCode::OK;
}
$migrations = array_keys($migrations);
$n = count($migrations);
$this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
foreach ($migrations as $migration) {
$this->stdout("\t$migration\n");
}
$this->stdout("\n");
$reverted = 0;
if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
foreach ($migrations as $migration) {
if (!$this->migrateDown($migration)) {
$this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
$this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$reverted++;
}
$this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
$this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::actionFresh()
すべてのテーブルと関連する制約を削除します。マイグレーションを最初から開始します。
yii migrate/fresh
public void actionFresh ( ) |
public function actionFresh()
{
if (YII_ENV_PROD) {
$this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n");
return ExitCode::OK;
}
if ($this->confirm("Are you sure you want to drop all tables and related constraints and start the migration from the beginning?\nAll data will be lost irreversibly!")) {
$this->truncateDatabase();
return $this->actionUp();
}
$this->stdout('Action was cancelled by user. Nothing has been performed.');
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::actionHistory()
マイグレーション履歴を表示します。
このコマンドは、これまでに適用されたマイグレーションのリストを表示します。例えば、
yii migrate/history # showing the last 10 migrations
yii migrate/history 5 # showing the last 5 migrations
yii migrate/history all # showing the whole history
public void actionHistory ( $limit = 10 ) | ||
$limit | integer|string |
表示するマイグレーションの最大数。 "all" の場合、マイグレーション履歴全体が表示されます。 |
throws | yii\console\Exception |
無効な limit 値が渡された場合 |
---|
public function actionHistory($limit = 10)
{
if ($limit === 'all') {
$limit = null;
} else {
$limit = (int) $limit;
if ($limit < 1) {
throw new Exception('The limit must be greater than 0.');
}
}
$migrations = $this->getMigrationHistory($limit);
if (empty($migrations)) {
$this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
} else {
$n = count($migrations);
if ($limit > 0) {
$this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
} else {
$this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
}
foreach ($migrations as $version => $time) {
$this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
}
}
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::actionMark()
マイグレーション履歴を指定されたバージョンに変更します。
実際のマイグレーションは実行されません。
yii migrate/mark 101129_185401 # using timestamp
yii migrate/mark m101129_185401_create_user_table # using full name
yii migrate/mark app\migrations\M101129185401CreateUser # using full namespace name
yii migrate/mark m000000_000000_base # reset the complete migration history
public integer actionMark ( $version ) | ||
$version | string |
マイグレーション履歴をマークするバージョン。これは、タイムスタンプまたはマイグレーションのフルネームのいずれかです。マイグレーション履歴を、マイグレーションが適用されていない状態に設定するには、名前 |
return | integer |
CLI 終了コード |
---|---|---|
throws | yii\console\Exception |
version 引数が無効であるか、バージョンが見つからない場合。 |
public function actionMark($version)
{
$originalVersion = $version;
if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
$version = $namespaceVersion;
} elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
$version = $migrationName;
} elseif ($version !== static::BASE_MIGRATION) {
throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable).");
}
// try mark up
$migrations = $this->getNewMigrations();
foreach ($migrations as $i => $migration) {
if (strpos($migration, $version) === 0) {
if ($this->confirm("Set migration history at $originalVersion?")) {
for ($j = 0; $j <= $i; ++$j) {
$this->addMigrationHistory($migrations[$j]);
}
$this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
}
// try mark down
$migrations = array_keys($this->getMigrationHistory(null));
$migrations[] = static::BASE_MIGRATION;
foreach ($migrations as $i => $migration) {
if (strpos($migration, $version) === 0) {
if ($i === 0) {
$this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
} elseif ($this->confirm("Set migration history at $originalVersion?")) {
for ($j = 0; $j < $i; ++$j) {
$this->removeMigrationHistory($migrations[$j]);
}
$this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
}
throw new Exception("Unable to find the version '$originalVersion'.");
}
定義元: yii\console\controllers\BaseMigrateController::actionNew()
適用されていない新しいマイグレーションを表示します。
このコマンドは、まだ適用されていない新しいマイグレーションを表示します。例えば、
yii migrate/new # showing the first 10 new migrations
yii migrate/new 5 # showing the first 5 new migrations
yii migrate/new all # showing all new migrations
public void actionNew ( $limit = 10 ) | ||
$limit | integer|string |
表示する新しいマイグレーションの最大数。 |
throws | yii\console\Exception |
無効な limit 値が渡された場合 |
---|
public function actionNew($limit = 10)
{
if ($limit !== 'all') {
$limit = (int) $limit;
if ($limit < 1) {
throw new Exception('The limit must be greater than 0.');
}
}
$migrations = $this->getNewMigrations();
if (empty($migrations)) {
$this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
} else {
$n = count($migrations);
if ($limit !== 'all' && $n > $limit) {
$migrations = array_slice($migrations, 0, $limit);
$this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
} else {
$this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
}
foreach ($migrations as $migration) {
$this->stdout("\t" . $migration . "\n");
}
}
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::actionRedo()
最後の数個のマイグレーションをやり直します。
このコマンドは、まず指定されたマイグレーションをロールバックし、次に再度適用します。例えば、
yii migrate/redo # redo the last applied migration
yii migrate/redo 3 # redo the last 3 applied migrations
yii migrate/redo all # redo all migrations
public integer actionRedo ( $limit = 1 ) | ||
$limit | integer|string |
やり直すマイグレーションの数。デフォルトは 1 で、最後に適用されたマイグレーションがやり直されることを意味します。"all" と等しい場合、すべてのマイグレーションがやり直されます。 |
return | integer |
アクション実行の状態。0 は正常、それ以外の値は異常を意味します。 |
---|---|---|
throws | yii\console\Exception |
指定されたステップ数が 1 未満の場合。 |
public function actionRedo($limit = 1)
{
if ($limit === 'all') {
$limit = null;
} else {
$limit = (int) $limit;
if ($limit < 1) {
throw new Exception('The step argument must be greater than 0.');
}
}
$migrations = $this->getMigrationHistory($limit);
if (empty($migrations)) {
$this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
return ExitCode::OK;
}
$migrations = array_keys($migrations);
$n = count($migrations);
$this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
foreach ($migrations as $migration) {
$this->stdout("\t$migration\n");
}
$this->stdout("\n");
if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
foreach ($migrations as $migration) {
if (!$this->migrateDown($migration)) {
$this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
}
foreach (array_reverse($migrations) as $migration) {
if (!$this->migrateUp($migration)) {
$this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
}
$this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN);
$this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
定義場所: yii\console\controllers\BaseMigrateController::actionTo()
指定されたバージョンまでアップグレードまたはダウングレードします。
また、UNIXタイムスタンプまたはstrtotime()関数で解析可能な文字列を指定することで、過去の特定の適用時間までバージョンをダウングレードすることもできます。これは、指定された特定の時間以降に適用されたすべてのバージョンが元に戻されることを意味します。
このコマンドは、まず指定されたマイグレーションをロールバックし、次に再度適用します。例えば、
yii migrate/to 101129_185401 # using timestamp
yii migrate/to m101129_185401_create_user_table # using full name
yii migrate/to 1392853618 # using UNIX timestamp
yii migrate/to "2014-02-15 13:00:50" # using strtotime() parseable string
yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
public void actionTo ( $version ) | ||
$version | string |
アプリケーションを移行する必要がある過去のバージョン名または特定の時間値のいずれか。これは、タイムスタンプ、マイグレーションのフルネーム、UNIXタイムスタンプ、または解析可能な日時文字列のいずれかです。 |
throws | yii\console\Exception |
バージョン引数が無効な場合。 |
---|
public function actionTo($version)
{
if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
return $this->migrateToVersion($namespaceVersion);
} elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
return $this->migrateToVersion($migrationName);
} elseif ((string) (int) $version == $version) {
return $this->migrateToTime($version);
} elseif (($time = strtotime($version)) !== false) {
return $this->migrateToTime($time);
} else {
throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401),\n the full name of a migration (e.g. m101129_185401_create_user_table),\n the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50).");
}
}
定義場所: yii\console\controllers\BaseMigrateController::actionUp()
新しいマイグレーションを適用することでアプリケーションをアップグレードします。
例えば、
yii migrate # apply all new migrations
yii migrate 3 # apply the first 3 new migrations
public integer actionUp ( $limit = 0 ) | ||
$limit | integer |
適用する新しいマイグレーションの数。0の場合は、利用可能なすべての新しいマイグレーションを適用することを意味します。 |
return | integer |
アクション実行の状態。0 は正常、それ以外の値は異常を意味します。 |
---|
public function actionUp($limit = 0)
{
$migrations = $this->getNewMigrations();
if (empty($migrations)) {
$this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
return ExitCode::OK;
}
$total = count($migrations);
$limit = (int) $limit;
if ($limit > 0) {
$migrations = array_slice($migrations, 0, $limit);
}
$n = count($migrations);
if ($n === $total) {
$this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
} else {
$this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
}
foreach ($migrations as $migration) {
$nameLimit = $this->getMigrationNameLimit();
if ($nameLimit !== null && strlen($migration) > $nameLimit) {
$this->stdout("\nThe migration name '$migration' is too long. Its not possible to apply this migration.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("\t$migration\n");
}
$this->stdout("\n");
$applied = 0;
if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
foreach ($migrations as $migration) {
if (!$this->migrateUp($migration)) {
$this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED);
$this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$applied++;
}
$this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN);
$this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
}
return ExitCode::OK;
}
定義場所: yii\base\Controller::actions()
コントローラーの外部アクションを宣言します。
このメソッドは、コントローラの外部アクションを宣言するために上書きされることを意図しています。アクションIDを配列キーとし、対応するアクションクラス名またはアクション構成配列を配列値とする配列を返す必要があります。例えば、
return [
'action1' => 'app\components\Action1',
'action2' => [
'class' => 'app\components\Action2',
'property1' => 'value1',
'property2' => 'value2',
],
];
Yii::createObject() は、ここで提供された構成を使用して、リクエストされたアクションを作成するために後で使用されます。
public array actions ( ) |
public function actions()
{
return [];
}
主キーが指定されていない場合、デフォルトの主キーをフィールドリストに追加します。
protected void addDefaultPrimaryKey ( &$fields ) | ||
$fields | array |
解析されたフィールド |
protected function addDefaultPrimaryKey(&$fields)
{
foreach ($fields as $field) {
if ($field['property'] === 'id' || false !== strripos($field['decorators'], 'primarykey()')) {
return;
}
}
array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
}
新しいマイグレーションエントリを履歴に追加します。
protected void addMigrationHistory ( $version ) | ||
$version | string |
マイグレーションバージョン名。 |
protected function addMigrationHistory($version)
{
$command = $this->db->createCommand();
$command->insert($this->migrationTable, [
'version' => $version,
'apply_time' => time(),
])->execute();
}
定義場所: yii\base\Controller::afterAction()
このメソッドはアクションが実行された直後に呼び出されます。
このメソッドは、EVENT_AFTER_ACTIONイベントをトリガーします。メソッドの戻り値は、アクションの戻り値として使用されます。
このメソッドをオーバーライドする場合は、コードは次のようになります
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
return $result;
}
public mixed afterAction ( $action, $result ) | ||
$action | yii\base\Action |
実行されたばかりのアクション。 |
$result | mixed |
アクションの戻り結果。 |
return | mixed |
処理済みのアクション結果。 |
---|
public function afterAction($action, $result)
{
$event = new ActionEvent($action);
$event->result = $result;
$this->trigger(self::EVENT_AFTER_ACTION, $event);
return $event->result;
}
定義場所: yii\console\Controller::ansiFormat()
ANSIコードで文字列をフォーマットします。
yii\helpers\Consoleで定義された定数を使用して、追加のパラメーターを渡すことができます。
例
echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public string ansiFormat ( $string ) | ||
$string | string |
フォーマットする文字列 |
public function ansiFormat($string)
{
if ($this->isColorEnabled()) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return $string;
}
定義場所: yii\base\Component::attachBehavior()
ビヘイビアをこのコンポーネントにアタッチします。
このメソッドは、指定された構成に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach()メソッドを呼び出すことによって、ビヘイビアオブジェクトがこのコンポーネントにアタッチされます。
参照 detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
ビヘイビアの名前。 |
$behavior | string|array|yii\base\Behavior |
ビヘイビア構成。これは、次のいずれかになります
|
return | yii\base\Behavior |
ビヘイビアオブジェクト |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義場所: yii\base\Component::attachBehaviors()
ビヘイビアのリストをコンポーネントにアタッチします。
各ビヘイビアは、その名前でインデックス付けされており、yii\base\Behaviorオブジェクト、ビヘイビアクラスを指定する文字列、またはビヘイビアを作成するための構成配列である必要があります。
参照 attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
コンポーネントにアタッチするビヘイビアのリスト |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
このメソッドは、(可能なすべてのフィルターの後)アクションが実行される直前に呼び出されます。これは$migrationPathの存在を確認します。
public boolean beforeAction ( $action ) | ||
$action | yii\base\Action |
実行されるアクション。 |
return | boolean |
アクションを実行し続ける必要があるかどうか。 |
---|
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
$this->db = Instance::ensure($this->db, Connection::className());
return true;
}
return false;
}
定義元: yii\base\Component::behaviors()
このコンポーネントが動作するべきビヘイビアのリストを返します。
子クラスは、自身が動作させたいビヘイビアを指定するために、このメソッドをオーバーライドすることができます。
このメソッドの戻り値は、ビヘイビアの名前をキーとするビヘイビアオブジェクトまたは構成の配列である必要があります。ビヘイビア構成は、ビヘイビアクラスを指定する文字列か、以下の構造の配列のいずれかになります。
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
ビヘイビアクラスは yii\base\Behavior から拡張する必要があることに注意してください。ビヘイビアは名前を使用するか、匿名でアタッチすることができます。配列のキーとして名前を使用した場合、この名前を使用して、後で getBehavior() を使用してビヘイビアを取得したり、detachBehavior() を使用してデタッチしたりすることができます。匿名ビヘイビアは、取得またはデタッチできません。
このメソッドで宣言されたビヘイビアは、自動的に(要求に応じて)コンポーネントにアタッチされます。
public array behaviors ( ) | ||
return | array |
ビヘイビアの構成。 |
---|
public function behaviors()
{
return [];
}
定義元: yii\console\Controller::bindActionParams()
アクションにパラメータをバインドします。
このメソッドは、指定されたパラメータで実行を開始するときに、yii\base\Action によって呼び出されます。このメソッドは、まず、アクションで利用可能な options でパラメータをバインドします。次に、与えられた引数を検証します。
public array bindActionParams ( $action, $params ) | ||
$action | yii\base\Action |
パラメータでバインドされるアクション |
$params | array |
アクションにバインドされるパラメータ |
return | array |
アクションが実行できる有効なパラメータ。 |
---|---|---|
throws | yii\console\Exception |
不明なオプションまたは不足している引数がある場合 |
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = [];
$missing = [];
$actionParams = [];
$requestedParams = [];
foreach ($method->getParameters() as $i => $param) {
$name = $param->getName();
$key = null;
if (array_key_exists($i, $params)) {
$key = $i;
} elseif (array_key_exists($name, $params)) {
$key = $name;
}
if ($key !== null) {
if (PHP_VERSION_ID >= 80000) {
$isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
} else {
$isArray = $param->isArray();
}
if ($isArray) {
$params[$key] = $params[$key] === '' ? [] : preg_split('/\s*,\s*/', $params[$key]);
}
$args[] = $actionParams[$key] = $params[$key];
unset($params[$key]);
} elseif (
PHP_VERSION_ID >= 70100
&& ($type = $param->getType()) !== null
&& $type instanceof \ReflectionNamedType
&& !$type->isBuiltin()
) {
try {
$this->bindInjectedParams($type, $name, $args, $requestedParams);
} catch (\yii\base\Exception $e) {
throw new Exception($e->getMessage());
}
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $actionParams[$i] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if (!empty($missing)) {
throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
}
// We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
if (\Yii::$app->requestedParams === null) {
\Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
}
return array_merge($args, $params);
}
定義元: yii\base\Controller::bindInjectedParams()
アクションメソッドシグネチャの型と名前に基づいてパラメータを設定します。
protected void bindInjectedParams ( ReflectionType $type, $name, &$args, &$requestedParams ) | ||
$type | ReflectionType |
アクションパラメータのリフレクション型。 |
$name | string |
パラメータの名前。 |
$args | array |
アクションの引数の配列。この関数は、アイテムをそれに追加することがあります。 |
$requestedParams | array |
要求されたパラメータの配列。この関数は、特定のキーを書き込むことがあります。 |
throws | yii\base\ErrorException |
必要なサービスをロードできない場合。 |
---|---|---|
throws | yii\base\InvalidConfigException |
DI構成にエラーがある場合にスローされます。 |
throws | yii\di\NotInstantiableException |
コンテナに適切な定義がない場合、定義を具体的なクラス(たとえばインターフェース型ヒント)に解決できない場合にスローされます。 |
final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
{
// Since it is not a builtin type it must be DI injection.
$typeName = $type->getName();
if (($component = $this->module->get($name, false)) instanceof $typeName) {
$args[] = $component;
$requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
} elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
} elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = "Container DI: $typeName \$$name";
} elseif ($type->allowsNull()) {
$args[] = null;
$requestedParams[$name] = "Unavailable service: $name";
} else {
throw new Exception('Could not load required service: ' . $name);
}
}
定義元: yii\base\Component::canGetProperty()
プロパティが読み取り可能かどうかを示す値を返します。
プロパティが読み取り可能となるのは、以下のいずれかの場合です。
- クラスが、指定された名前に関連付けられたゲッターメソッドを持っている場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが、指定された名前のメンバ変数を持っている場合(
$checkVars
が true の場合)。 - アタッチされたビヘイビアが、指定された名前の読み取り可能なプロパティを持っている場合(
$checkBehaviors
が true の場合)。
参照:canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが読み取り可能かどうか |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
定義元: yii\base\Component::canSetProperty()
プロパティが設定可能かどうかを示す値を返します。
プロパティが書き込み可能となるのは、以下のいずれかの場合です。
- クラスが、指定された名前に関連付けられたセッターメソッドを持っている場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが、指定された名前のメンバ変数を持っている場合(
$checkVars
が true の場合)。 - アタッチされたビヘイビアが、指定された名前の書き込み可能なプロパティを持っている場合(
$checkBehaviors
が true の場合)。
参照:canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが書き込み可能かどうか |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
を使用してください。
定義元: yii\base\BaseObject::className()
このクラスの完全修飾名を返します。
public static string className ( ) | ||
return | string |
このクラスの完全修飾名。 |
---|
public static function className()
{
return get_called_class();
}
定義元: yii\console\Controller::confirm()
yまたはnを入力して確認するようにユーザーに求めます。
一般的な使用法は以下のようになります。
if ($this->confirm("Are you sure?")) {
echo "user typed yes\n";
} else {
echo "user typed no\n";
}
public boolean confirm ( $message, $default = false ) | ||
$message | string |
ユーザー入力を待つ前に出力するメッセージ |
$default | boolean |
選択が行われなかった場合に返される値。 |
return | boolean |
ユーザーが確認したかどうか。$interactive が false の場合は true が返されます。 |
---|
public function confirm($message, $default = false)
{
if ($this->interactive) {
return Console::confirm($message, $default);
}
return true;
}
定義元: yii\base\Controller::createAction()
指定されたアクションIDに基づいてアクションを作成します。
このメソッドは、まずアクション ID が actions() で宣言されているかどうかを確認します。宣言されている場合は、そこで宣言された構成を使用してアクションオブジェクトを作成します。宣言されていない場合は、コントローラメソッドで actionXyz
の形式の名前のメソッドを探します。ここで、xyz
はアクション ID です。見つかった場合は、そのメソッドを表す yii\base\InlineAction が作成され、返されます。
public yii\base\Action|null createAction ( $id ) | ||
$id | string |
アクションID。 |
return | yii\base\Action|null |
新しく作成されたアクションのインスタンス。IDがどのアクションにも解決されない場合はnull。 |
---|
public function createAction($id)
{
if ($id === '') {
$id = $this->defaultAction;
}
$actionMap = $this->actions();
if (isset($actionMap[$id])) {
return Yii::createObject($actionMap[$id], [$id, $this]);
}
if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
$methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
if (method_exists($this, $methodName)) {
$method = new \ReflectionMethod($this, $methodName);
if ($method->isPublic() && $method->getName() === $methodName) {
return new InlineAction($id, $this, $methodName);
}
}
}
return null;
}
新しいマイグレーションインスタンスを作成します。
protected yii\db\Migration createMigration ( $class ) | ||
$class | string |
マイグレーションクラス名 |
return | yii\db\Migration |
マイグレーションのインスタンス |
---|
protected function createMigration($class)
{
$this->includeMigrationFile($class);
return Yii::createObject([
'class' => $class,
'db' => $this->db,
'compact' => $this->compact,
]);
}
マイグレーション履歴テーブルを作成します。
protected void createMigrationHistoryTable ( ) |
protected function createMigrationHistoryTable()
{
$tableName = $this->db->schema->getRawTableName($this->migrationTable);
$this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
$this->db->createCommand()->createTable($this->migrationTable, [
'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY',
'apply_time' => 'integer',
])->execute();
$this->db->createCommand()->insert($this->migrationTable, [
'version' => self::BASE_MIGRATION,
'apply_time' => time(),
])->execute();
$this->stdout("Done.\n", Console::FG_GREEN);
}
定義元: yii\base\Component::detachBehavior()
コンポーネントからビヘイビアをデタッチします。
ビヘイビアの yii\base\Behavior::detach() メソッドが呼び出されます。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
ビヘイビアの名前。 |
return | yii\base\Behavior|null |
切り離されたビヘイビア。ビヘイビアが存在しない場合はNull。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
定義元: yii\base\Component::detachBehaviors()
コンポーネントからすべてのビヘイビアをデタッチします。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義元: yii\base\Component::ensureBehaviors()
behaviors()で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
定義元: yii\base\Controller::findLayoutFile()
適用可能なレイアウトファイルを見つけます。
public string|boolean findLayoutFile ( $view ) | ||
$view | yii\base\View |
レイアウトファイルをレンダリングするビューオブジェクト。 |
return | string|boolean |
レイアウトファイルのパス、またはレイアウトが不要な場合はfalse。このパラメータの指定方法については、render() を参照してください。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
レイアウトを指定するために無効なパスエイリアスが使用された場合。 |
public function findLayoutFile($view)
{
$module = $this->module;
$layout = null;
if (is_string($this->layout)) {
$layout = $this->layout;
} elseif ($this->layout === null) {
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module !== null && is_string($module->layout)) {
$layout = $module->layout;
}
}
if ($layout === null) {
return false;
}
if (strncmp($layout, '@', 1) === 0) {
$file = Yii::getAlias($layout);
} elseif (strncmp($layout, '/', 1) === 0) {
$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
} else {
$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
}
if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
return $file;
}
$path = $file . '.' . $view->defaultExtension;
if ($view->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
}
新しいマイグレーションソースPHPコードを生成します。
子クラスはこのメソッドをオーバーライドして、プロセスに追加のロジックまたはバリエーションを加えることができます。
protected string generateMigrationSourceCode ( $params ) | ||
$params | array |
生成パラメータ。通常、以下のパラメータが存在します。
|
return | string |
生成されたPHPコード。 |
---|
protected function generateMigrationSourceCode($params)
{
$parsedFields = $this->parseFields();
$fields = $parsedFields['fields'];
$foreignKeys = $parsedFields['foreignKeys'];
$name = $params['name'];
if ($params['namespace']) {
$name = substr($name, (strrpos($name, '\\') ?: -1) + 1);
}
$templateFile = $this->templateFile;
$table = null;
if (preg_match('/^create_?junction_?(?:table)?_?(?:for)?(.+)_?and(.+)_?tables?$/i', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['create_junction'];
$firstTable = $this->normalizeTableName($matches[1]);
$secondTable = $this->normalizeTableName($matches[2]);
$fields = array_merge(
[
[
'property' => $firstTable . '_id',
'decorators' => 'integer()',
],
[
'property' => $secondTable . '_id',
'decorators' => 'integer()',
],
],
$fields,
[
[
'property' => 'PRIMARY KEY(' .
$firstTable . '_id, ' .
$secondTable . '_id)',
],
]
);
$foreignKeys[$firstTable . '_id']['table'] = $firstTable;
$foreignKeys[$secondTable . '_id']['table'] = $secondTable;
$foreignKeys[$firstTable . '_id']['column'] = null;
$foreignKeys[$secondTable . '_id']['column'] = null;
$table = $firstTable . '_' . $secondTable;
} elseif (preg_match('/^add(.+)columns?_?to(.+)table$/i', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['add_column'];
$table = $this->normalizeTableName($matches[2]);
} elseif (preg_match('/^drop(.+)columns?_?from(.+)table$/i', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['drop_column'];
$table = $this->normalizeTableName($matches[2]);
} elseif (preg_match('/^create(.+)table$/i', $name, $matches)) {
$this->addDefaultPrimaryKey($fields);
$templateFile = $this->generatorTemplateFiles['create_table'];
$table = $this->normalizeTableName($matches[1]);
} elseif (preg_match('/^drop(.+)table$/i', $name, $matches)) {
$this->addDefaultPrimaryKey($fields);
$templateFile = $this->generatorTemplateFiles['drop_table'];
$table = $this->normalizeTableName($matches[1]);
}
foreach ($foreignKeys as $column => $foreignKey) {
$relatedColumn = $foreignKey['column'];
$relatedTable = $foreignKey['table'];
// Since 2.0.11 if related column name is not specified,
// we're trying to get it from table schema
// @see https://github.com/yiisoft/yii2/issues/12748
if ($relatedColumn === null) {
$relatedColumn = 'id';
try {
$this->db = Instance::ensure($this->db, Connection::className());
$relatedTableSchema = $this->db->getTableSchema($relatedTable);
if ($relatedTableSchema !== null) {
$primaryKeyCount = count($relatedTableSchema->primaryKey);
if ($primaryKeyCount === 1) {
$relatedColumn = $relatedTableSchema->primaryKey[0];
} elseif ($primaryKeyCount > 1) {
$this->stdout("Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field\n", Console::FG_YELLOW);
} elseif ($primaryKeyCount === 0) {
$this->stdout("Related table for field \"{$column}\" exists, but does not have a primary key. Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
}
}
} catch (\ReflectionException $e) {
$this->stdout("Cannot initialize database component to try reading referenced table schema for field \"{$column}\". Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
}
}
$foreignKeys[$column] = [
'idx' => $this->generateTableName("idx-$table-$column"),
'fk' => $this->generateTableName("fk-$table-$column"),
'relatedTable' => $this->generateTableName($relatedTable),
'relatedColumn' => $relatedColumn,
];
}
return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
'table' => $this->generateTableName($table),
'fields' => $fields,
'foreignKeys' => $foreignKeys,
'tableComment' => $this->comment,
]));
}
useTablePrefix
がtrueの場合、テーブル名には接頭辞の形式が含まれます。
protected string generateTableName ( $tableName ) | ||
$tableName | string |
生成するテーブル名。 |
protected function generateTableName($tableName)
{
if (!$this->useTablePrefix) {
return $tableName;
}
return '{{%' . $tableName . '}}';
}
定義元: yii\console\Controller::getActionArgsHelp()
アクションの匿名引数のヘルプ情報を返します。
返される値は配列である必要があります。キーは引数名、値は対応するヘルプ情報です。各値は以下の構造の配列でなければなりません。
- required: bool, この引数が必須かどうか
- type: string|null, この引数のPHPの型
- default: mixed, この引数のデフォルト値
- comment: string, この引数の説明
デフォルトの実装では、アクションメソッドに対応するパラメータのリフレクションまたは DocBlock から抽出されたヘルプ情報が返されます。
public array getActionArgsHelp ( $action ) | ||
$action | yii\base\Action |
アクションのインスタンス |
return | array |
アクション引数のヘルプ情報 |
---|
public function getActionArgsHelp($action)
{
$method = $this->getActionMethodReflection($action);
$tags = $this->parseDocCommentTags($method);
$tags['param'] = isset($tags['param']) ? (array) $tags['param'] : [];
$phpDocParams = [];
foreach ($tags['param'] as $i => $tag) {
if (preg_match('/^(?<type>\S+)(\s+\$(?<name>\w+))?(?<comment>.*)/us', $tag, $matches) === 1) {
$key = empty($matches['name']) ? $i : $matches['name'];
$phpDocParams[$key] = ['type' => $matches['type'], 'comment' => $matches['comment']];
}
}
unset($tags);
$args = [];
/** @var \ReflectionParameter $parameter */
foreach ($method->getParameters() as $i => $parameter) {
$type = null;
$comment = '';
if (PHP_MAJOR_VERSION > 5 && $parameter->hasType()) {
$reflectionType = $parameter->getType();
if (PHP_VERSION_ID >= 70100) {
$types = method_exists($reflectionType, 'getTypes') ? $reflectionType->getTypes() : [$reflectionType];
foreach ($types as $key => $reflectionType) {
$types[$key] = $reflectionType->getName();
}
$type = implode('|', $types);
} else {
$type = (string) $reflectionType;
}
}
// find PhpDoc tag by property name or position
$key = isset($phpDocParams[$parameter->name]) ? $parameter->name : (isset($phpDocParams[$i]) ? $i : null);
if ($key !== null) {
$comment = $phpDocParams[$key]['comment'];
if ($type === null && !empty($phpDocParams[$key]['type'])) {
$type = $phpDocParams[$key]['type'];
}
}
// if type still not detected, then using type of default value
if ($type === null && $parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() !== null) {
$type = gettype($parameter->getDefaultValue());
}
$args[$parameter->name] = [
'required' => !$parameter->isOptional(),
'type' => $type,
'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
'comment' => $comment,
];
}
return $args;
}
定義元: yii\console\Controller::getActionHelp()
指定されたアクションの詳細なヘルプ情報を返します。
public string getActionHelp ( $action ) | ||
$action | yii\base\Action |
ヘルプを取得するアクション |
return | string |
指定されたアクションの詳細なヘルプ情報。 |
---|
public function getActionHelp($action)
{
return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
}
定義元: yii\console\Controller::getActionHelpSummary()
指定されたアクションを説明する1行の短い概要を返します。
public string getActionHelpSummary ( $action ) | ||
$action | yii\base\Action |
概要を取得するアクション |
return | string |
指定されたアクションを説明する1行の短い概要。 |
---|
public function getActionHelpSummary($action)
{
if ($action === null) {
return $this->ansiFormat(Yii::t('yii', 'Action not found.'), Console::FG_RED);
}
return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
}
protected ReflectionFunctionAbstract getActionMethodReflection ( $action ) | ||
$action | yii\base\Action |
protected function getActionMethodReflection($action)
{
if (!isset($this->_reflections[$action->id])) {
if ($action instanceof InlineAction) {
$this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
} else {
$this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
}
}
return $this->_reflections[$action->id];
}
定義元: yii\console\Controller::getActionOptionsHelp()
アクションのオプションのヘルプ情報を返します。
返り値は配列である必要があります。キーはオプション名、値は対応するヘルプ情報です。各値は、次の構造の配列でなければなりません。
- type: string, この引数のPHP型。
- default: string, この引数のデフォルト値
- comment: string, この引数のコメント
デフォルトの実装では、アクションオプションに対応するプロパティのドキュメントコメントから抽出されたヘルプ情報を返します。
public array getActionOptionsHelp ( $action ) | ||
$action | yii\base\Action | |
return | array |
アクションオプションのヘルプ情報 |
---|
public function getActionOptionsHelp($action)
{
$optionNames = $this->options($action->id);
if (empty($optionNames)) {
return [];
}
$class = new \ReflectionClass($this);
$options = [];
foreach ($class->getProperties() as $property) {
$name = $property->getName();
if (!in_array($name, $optionNames, true)) {
continue;
}
$defaultValue = $property->getValue($this);
$tags = $this->parseDocCommentTags($property);
// Display camelCase options in kebab-case
$name = Inflector::camel2id($name, '-', true);
if (isset($tags['var']) || isset($tags['property'])) {
$doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
if (is_array($doc)) {
$doc = reset($doc);
}
if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
$type = $matches[1];
$comment = $matches[2];
} else {
$type = null;
$comment = $doc;
}
$options[$name] = [
'type' => $type,
'default' => $defaultValue,
'comment' => $comment,
];
} else {
$options[$name] = [
'type' => null,
'default' => $defaultValue,
'comment' => '',
];
}
}
return $options;
}
定義元: yii\base\Component::getBehavior()
名前付きのビヘイビアオブジェクトを返します。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
ビヘイビア名 |
return | yii\base\Behavior|null |
ビヘイビアオブジェクト、またはビヘイビアが存在しない場合は null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義元: yii\base\Component::getBehaviors()
このコンポーネントにアタッチされたすべてのビヘイビアを返します。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
このコンポーネントにアタッチされたビヘイビアのリスト |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
定義元: yii\console\Controller::getHelp()
このコントローラーのヘルプ情報を返します。
このメソッドをオーバーライドして、カスタマイズされたヘルプを返すことができます。デフォルトの実装では、PHPDocコメントから取得したヘルプ情報を返します。
public string getHelp ( ) |
public function getHelp()
{
return $this->parseDocCommentDetail(new \ReflectionClass($this));
}
定義元: yii\console\Controller::getHelpSummary()
このコントローラーを説明する1行の短い概要を返します。
このメソッドをオーバーライドして、カスタマイズされたサマリーを返すことができます。デフォルトの実装では、PHPDocコメントの最初の行を返します。
public string getHelpSummary ( ) |
public function getHelpSummary()
{
return $this->parseDocCommentSummary(new \ReflectionClass($this));
}
マイグレーション履歴を返します。
protected array getMigrationHistory ( $limit ) | ||
$limit | integer|null |
返される履歴の最大レコード数。"制限なし"の場合は |
return | array |
マイグレーション履歴 |
---|
protected function getMigrationHistory($limit)
{
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$query = (new Query())
->select(['version', 'apply_time'])
->from($this->migrationTable)
->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
if (empty($this->migrationNamespaces)) {
$query->limit($limit);
$rows = $query->all($this->db);
$history = ArrayHelper::map($rows, 'version', 'apply_time');
unset($history[self::BASE_MIGRATION]);
return $history;
}
$rows = $query->all($this->db);
$history = [];
foreach ($rows as $key => $row) {
if ($row['version'] === self::BASE_MIGRATION) {
continue;
}
if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
$time = str_replace('_', '', $matches[1]);
$row['canonicalVersion'] = $time;
} else {
$row['canonicalVersion'] = $row['version'];
}
$row['apply_time'] = (int) $row['apply_time'];
$history[] = $row;
}
usort($history, function ($a, $b) {
if ($a['apply_time'] === $b['apply_time']) {
if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
return $compareResult;
}
return strcasecmp($b['version'], $a['version']);
}
return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
});
$history = array_slice($history, 0, $limit);
$history = ArrayHelper::map($history, 'version', 'apply_time');
return $history;
}
マイグレーションの最大名前長を返します。
サブクラスは、このメソッドをオーバーライドして制限を定義できます。
protected integer|null getMigrationNameLimit ( ) | ||
return | integer|null |
マイグレーションの最大名前長、または制限がない場合は |
---|
protected function getMigrationNameLimit()
{
if ($this->_migrationNameLimit !== null) {
return $this->_migrationNameLimit;
}
$tableSchema = $this->db->schema ? $this->db->schema->getTableSchema($this->migrationTable, true) : null;
if ($tableSchema !== null) {
return $this->_migrationNameLimit = $tableSchema->columns['version']->size;
}
return static::MAX_NAME_LENGTH;
}
定義元: yii\base\Controller::getModules()
このコントローラーのすべての上位モジュールを返します。
配列の最初のモジュールは最も外側のモジュール (つまり、アプリケーションインスタンス) であり、最後は最も内側のモジュールです。
public yii\base\Module[] getModules ( ) | ||
return | yii\base\Module[] |
このコントローラが配置されているすべての上位モジュール。 |
---|
public function getModules()
{
$modules = [$this->module];
$module = $this->module;
while ($module->module !== null) {
array_unshift($modules, $module->module);
$module = $module->module;
}
return $modules;
}
定義元: yii\console\controllers\BaseMigrateController::getNewMigrations()
適用されていないマイグレーションを返します。
protected array getNewMigrations ( ) | ||
return | array |
新しいマイグレーションのリスト |
---|
protected function getNewMigrations()
{
$applied = [];
foreach ($this->getMigrationHistory(null) as $class => $time) {
$applied[trim($class, '\\')] = true;
}
$migrationPaths = [];
if (is_array($this->migrationPath)) {
foreach ($this->migrationPath as $path) {
$migrationPaths[] = [$path, ''];
}
} elseif (!empty($this->migrationPath)) {
$migrationPaths[] = [$this->migrationPath, ''];
}
foreach ($this->migrationNamespaces as $namespace) {
$migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
}
$migrations = [];
foreach ($migrationPaths as $item) {
list($migrationPath, $namespace) = $item;
if (!file_exists($migrationPath)) {
continue;
}
$handle = opendir($migrationPath);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $migrationPath . DIRECTORY_SEPARATOR . $file;
if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
$class = $matches[1];
if (!empty($namespace)) {
$class = $namespace . '\\' . $class;
}
$time = str_replace('_', '', $matches[2]);
if (!isset($applied[$class])) {
$migrations[$time . '\\' . $class] = $class;
}
}
}
closedir($handle);
}
ksort($migrations);
return array_values($migrations);
}
定義元: yii\console\Controller::getOptionValues()
アクションIDのオプションに対応するプロパティを返します。子クラスはこのメソッドをオーバーライドして、可能なプロパティを指定できます。
public array getOptionValues ( $actionID ) | ||
$actionID | string |
現在のリクエストのアクションID |
return | array |
アクションのオプションに対応するプロパティ |
---|
public function getOptionValues($actionID)
{
// $actionId might be used in subclasses to provide properties specific to action id
$properties = [];
foreach ($this->options($this->action->id) as $property) {
$properties[$property] = $this->$property;
}
return $properties;
}
定義元: yii\console\Controller::getPassedOptionValues()
渡されたオプションに対応するプロパティを返します。
public array getPassedOptionValues ( ) | ||
return | array |
渡されたオプションに対応するプロパティ |
---|
public function getPassedOptionValues()
{
$properties = [];
foreach ($this->_passedOptions as $property) {
$properties[$property] = $this->$property;
}
return $properties;
}
定義元: yii\console\Controller::getPassedOptions()
実行中に渡された有効なオプションの名前を返します。
public array getPassedOptions ( ) | ||
return | array |
実行時に渡されたオプションの名前 |
---|
public function getPassedOptions()
{
return $this->_passedOptions;
}
定義元: yii\base\Controller::getRoute()
現在のリクエストのルートを返します。
public string getRoute ( ) | ||
return | string |
現在のリクエストのルート(モジュール ID、コントローラ ID、およびアクション ID)。 |
---|
public function getRoute()
{
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}
定義元: yii\base\Controller::getUniqueId()
コントローラーの一意のIDを返します。
public string getUniqueId ( ) | ||
return | string |
モジュールID(もしあれば)が接頭辞として付いたコントローラーID。 |
---|
public function getUniqueId()
{
return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
}
定義元: yii\base\Controller::getView()
ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクトを返します。
render(), renderPartial() および renderFile() メソッドは、実際のビューのレンダリングを実装するために、このビューオブジェクトを使用します。設定されていない場合は、デフォルトで「view」アプリケーションコンポーネントになります。
public yii\base\View|yii\web\View getView ( ) | ||
return | yii\base\View|yii\web\View |
ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクト。 |
---|
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
定義元: yii\base\Controller::getViewPath()
このコントローラーのビューファイルが含まれるディレクトリを返します。
デフォルトの実装では、コントローラの $id と同じ名前のディレクトリを、$module の $viewPath ディレクトリの下に返します。
public string getViewPath ( ) | ||
return | string |
このコントローラーのビューファイルが含まれるディレクトリ。 |
---|
public function getViewPath()
{
if ($this->_viewPath === null) {
$this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
}
return $this->_viewPath;
}
定義元: yii\base\Component::hasEventHandlers()
名前付きイベントにアタッチされたハンドラーがあるかどうかを示す値を返します。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
イベント名 |
return | boolean |
イベントにハンドラーがアタッチされているかどうか。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義元: yii\base\Component::hasMethod()
メソッドが定義されているかどうかを示す値を返します。
メソッドが定義されているのは、
- クラスが指定された名前のメソッドを持っている場合
- アタッチされたビヘイビアが指定された名前のメソッドを持っている場合 (
$checkBehaviors
が true の場合)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkBehaviors | boolean |
ビヘイビアのメソッドをこのコンポーネントのメソッドとして扱うかどうか |
return | boolean |
メソッドが定義されているかどうか |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義元: yii\base\Component::hasProperty()
このコンポーネントにプロパティが定義されているかどうかを示す値を返します。
プロパティが定義されているのは、
- クラスが指定された名前に関連付けられたゲッターまたはセッターメソッドを持っている場合 (この場合、プロパティ名は大文字と小文字が区別されません)。
- クラスが、指定された名前のメンバ変数を持っている場合(
$checkVars
が true の場合)。 - アタッチされたビヘイビアが指定された名前のプロパティを持っている場合 (
$checkBehaviors
が true の場合)。
こちらも参照
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが定義されているかどうか |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
定義元: yii\console\controllers\BaseMigrateController::includeMigrationFile()
指定されたマイグレーションクラス名のマイグレーションファイルを含めます。
この関数は、自動的にオートロードされる名前空間付きマイグレーションでは何も行いません。名前空間なしのクラスについて、$migrationPath を検索して、マイグレーションファイルを含めます。
protected void includeMigrationFile ( $class ) | ||
$class | string |
マイグレーションクラス名。 |
protected function includeMigrationFile($class)
{
$class = trim($class, '\\');
if (strpos($class, '\\') === false) {
if (is_array($this->migrationPath)) {
foreach ($this->migrationPath as $path) {
$file = $path . DIRECTORY_SEPARATOR . $class . '.php';
if (is_file($file)) {
require_once $file;
break;
}
}
} else {
$file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
require_once $file;
}
}
}
public void init ( ) |
public function init()
{
parent::init();
$this->request = Instance::ensure($this->request, Request::className());
$this->response = Instance::ensure($this->response, Response::className());
}
定義元: yii\console\Controller::isColorEnabled()
ANSIカラーが有効かどうかを示す値を返します。
ANSIカラーが有効になるのは、$color が true に設定されているか、設定されておらず、ターミナルが ANSI カラーをサポートしている場合のみです。
public boolean isColorEnabled ( $stream = \STDOUT ) | ||
$stream | リソース |
チェックするストリーム。 |
return | boolean |
出力で ANSI スタイルを有効にするかどうか。 |
---|
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}
定義元: yii\console\controllers\BaseMigrateController::migrateDown()
指定されたマイグレーションクラスでダウングレードします。
protected boolean migrateDown ( $class ) | ||
$class | string |
マイグレーションクラス名 |
return | boolean |
マイグレーションが成功したかどうか |
---|
protected function migrateDown($class)
{
if ($class === self::BASE_MIGRATION) {
return true;
}
$this->stdout("*** reverting $class\n", Console::FG_YELLOW);
$start = microtime(true);
$migration = $this->createMigration($class);
if ($migration->down() !== false) {
$this->removeMigrationHistory($class);
$time = microtime(true) - $start;
$this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
return true;
}
$time = microtime(true) - $start;
$this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
return false;
}
定義元: yii\console\controllers\BaseMigrateController::migrateToTime()
過去の指定された適用時間まで移行します。
protected void migrateToTime ( $time ) | ||
$time | integer |
UNIXタイムスタンプ値。 |
protected function migrateToTime($time)
{
$count = 0;
$migrations = array_values($this->getMigrationHistory(null));
while ($count < count($migrations) && $migrations[$count] > $time) {
++$count;
}
if ($count === 0) {
$this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
} else {
return $this->actionDown($count);
}
return ExitCode::OK;
}
定義元: yii\console\controllers\BaseMigrateController::migrateToVersion()
特定のバージョンに移行します。
protected integer migrateToVersion ( $version ) | ||
$version | string |
完全な形式の名前。 |
return | integer |
CLI 終了コード |
---|---|---|
throws | yii\console\Exception |
指定されたバージョンが見つからない場合。 |
protected function migrateToVersion($version)
{
$originalVersion = $version;
// try migrate up
$migrations = $this->getNewMigrations();
foreach ($migrations as $i => $migration) {
if (strpos($migration, $version) === 0) {
return $this->actionUp($i + 1);
}
}
// try migrate down
$migrations = array_keys($this->getMigrationHistory(null));
foreach ($migrations as $i => $migration) {
if (strpos($migration, $version) === 0) {
if ($i === 0) {
$this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
} else {
return $this->actionDown($i);
}
return ExitCode::OK;
}
}
throw new Exception("Unable to find the version '$originalVersion'.");
}
定義元: yii\console\controllers\BaseMigrateController::migrateUp()
指定されたマイグレーションクラスでアップグレードします。
protected boolean migrateUp ( $class ) | ||
$class | string |
マイグレーションクラス名 |
return | boolean |
マイグレーションが成功したかどうか |
---|
protected function migrateUp($class)
{
if ($class === self::BASE_MIGRATION) {
return true;
}
$this->stdout("*** applying $class\n", Console::FG_YELLOW);
$start = microtime(true);
$migration = $this->createMigration($class);
if ($migration->up() !== false) {
$this->addMigrationHistory($class);
$time = microtime(true) - $start;
$this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
return true;
}
$time = microtime(true) - $start;
$this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
return false;
}
定義元: yii\base\Component::off()
このコンポーネントから既存のイベントハンドラーをデタッチします。
このメソッドはon()の反対です。
注意: イベント名にワイルドカードパターンが渡された場合、このワイルドカードで登録されたハンドラーのみが削除され、このワイルドカードに一致するプレーンな名前で登録されたハンドラーは残ります。
こちらも参照してください: on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
イベント名 |
$handler | callable|null |
削除するイベントハンドラー。nullの場合、指定されたイベントにアタッチされたすべてのハンドラーが削除されます。 |
return | boolean |
ハンドラーが見つかり、デタッチされた場合 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
イベントにイベントハンドラーをアタッチします。
イベントハンドラーは有効なPHPコールバックである必要があります。以下にいくつかの例を示します
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
イベントハンドラーは、次のシグネチャで定義する必要があります。
function ($event)
ここで$event
は、イベントに関連付けられたパラメーターを含むyii\base\Eventオブジェクトです。
2.0.14以降、イベント名をワイルドカードパターンとして指定できます
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
こちらも参照してください: off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
イベント名 |
$handler | callable |
イベントハンドラー |
$data | mixed |
イベントがトリガーされたときにイベントハンドラーに渡されるデータ。イベントハンドラーが呼び出されると、このデータはyii\base\Event::$dataを介してアクセスできます。 |
$append | boolean |
既存のハンドラーリストの末尾に新しいイベントハンドラーを追加するかどうか。falseの場合、新しいハンドラーは既存のハンドラーリストの先頭に挿入されます。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
オプションのエイリアス名を返します。
子クラスは、このメソッドをオーバーライドしてエイリアスオプションを指定できます。
public array optionAliases ( ) | ||
return | array |
アクションで有効なオプションエイリアス名。キーはオプションのエイリアス名で、値はオプション名です。 |
---|
public function optionAliases()
{
return array_merge(parent::optionAliases(), [
'C' => 'comment',
'f' => 'fields',
'p' => 'migrationPath',
't' => 'migrationTable',
'F' => 'templateFile',
'P' => 'useTablePrefix',
'c' => 'compact',
]);
}
アクション(id)の有効なオプションの名前を返します。オプションには、名前がオプション名であるパブリックメンバー変数が存在する必要があります。
子クラスは、このメソッドをオーバーライドして可能なオプションを指定できます。
オプションで設定された値は、beforeAction()が呼び出されるまで利用できないことに注意してください。
public string[] options ( $actionID ) | ||
$actionID | string |
現在のリクエストのアクションID |
return | string[] |
アクションで有効なオプションの名前 |
---|
public function options($actionID)
{
return array_merge(
parent::options($actionID),
['migrationTable', 'db'], // global for all actions
$actionID === 'create'
? ['templateFile', 'fields', 'useTablePrefix', 'comment']
: []
);
}
定義元: yii\console\Controller::parseDocCommentDetail()
ドックブロックから完全な説明を返します。
protected string parseDocCommentDetail ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
protected function parseDocCommentDetail($reflection)
{
$comment = strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
$comment = trim(substr($comment, 0, $matches[0][1]));
}
if ($comment !== '') {
return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
}
return '';
}
定義元: yii\console\Controller::parseDocCommentSummary()
ドックブロックの最初の行を返します。
protected string parseDocCommentSummary ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
protected function parseDocCommentSummary($reflection)
{
$docLines = preg_split('~\R~u', $reflection->getDocComment());
if (isset($docLines[1])) {
return trim($docLines[1], "\t *");
}
return '';
}
定義元: yii\console\Controller::parseDocCommentTags()
コメントブロックをタグに解析します。
protected array parseDocCommentTags ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
コメントブロック |
return | array |
解析されたタグ |
---|
protected function parseDocCommentTags($reflection)
{
$comment = $reflection->getDocComment();
$comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($comment, '/'))), "\r", '');
$parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
$tags = [];
foreach ($parts as $part) {
if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
$name = $matches[1];
if (!isset($tags[$name])) {
$tags[$name] = trim($matches[2]);
} elseif (is_array($tags[$name])) {
$tags[$name][] = trim($matches[2]);
} else {
$tags[$name] = [$tags[$name], trim($matches[2])];
}
}
}
return $tags;
}
コマンドラインマイグレーションフィールドを解析します。
protected array parseFields ( ) | ||
return | array |
次のフィールドを持つ解析結果
|
---|
protected function parseFields()
{
$fields = [];
$foreignKeys = [];
foreach ($this->fields as $index => $field) {
$chunks = $this->splitFieldIntoChunks($field);
$property = array_shift($chunks);
foreach ($chunks as $i => &$chunk) {
if (strncmp($chunk, 'foreignKey', 10) === 0) {
preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
$foreignKeys[$property] = [
'table' => isset($matches[1])
? $matches[1]
: preg_replace('/_id$/', '', $property),
'column' => !empty($matches[2])
? $matches[2]
: null,
];
unset($chunks[$i]);
continue;
}
if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
$chunk .= '()';
}
}
$fields[] = [
'property' => $property,
'decorators' => implode('->', $chunks),
];
}
return [
'fields' => $fields,
'foreignKeys' => $foreignKeys,
];
}
定義元: yii\console\Controller::prompt()
ユーザーに入力を促し、それを検証します。
public string prompt ( $text, $options = [] ) | ||
$text | string |
プロンプト文字列 |
$options | array |
入力値を検証するためのオプション
validator 関数を使った prompt メソッドの使い方の例。
|
return | string |
ユーザー入力 |
---|
public function prompt($text, $options = [])
{
if ($this->interactive) {
return Console::prompt($text, $options);
}
return isset($options['default']) ? $options['default'] : '';
}
履歴から既存のマイグレーションを削除します。
protected void removeMigrationHistory ( $version ) | ||
$version | string |
マイグレーションバージョン名。 |
protected function removeMigrationHistory($version)
{
$command = $this->db->createCommand();
$command->delete($this->migrationTable, [
'version' => $version,
])->execute();
}
定義元: yii\base\Controller::render()
ビューをレンダリングし、利用可能な場合はレイアウトを適用します。
レンダリングされるビューは、以下のいずれかの形式で指定できます。
- パスエイリアス (例: "@app/views/site/index")
- アプリケーション内の絶対パス (例: "//site/index"): ビュー名が二重スラッシュで始まる場合。実際のビューファイルは、アプリケーションのビューパスの下で検索されます。
- モジュール内の絶対パス (例: "/site/index"): ビュー名が単一のスラッシュで始まる場合。実際のビューファイルは、$moduleのビューパスの下で検索されます。
- 相対パス (例: "index"): 実際のビューファイルは、$viewPathの下で検索されます。
適用されるレイアウトを決定するために、次の2つの手順が実行されます。
- 最初のステップでは、レイアウト名とコンテキストモジュールを決定します。
- $layoutが文字列として指定されている場合は、それをレイアウト名として使用し、$moduleをコンテキストモジュールとして使用します。
- $layoutがnullの場合は、このコントローラのすべての上位モジュールを検索し、layoutがnullではない最初のモジュールを見つけます。レイアウトと対応するモジュールが、それぞれレイアウト名とコンテキストモジュールとして使用されます。このようなモジュールが見つからないか、対応するレイアウトが文字列でない場合は、適用可能なレイアウトがないことを意味するfalseを返します。
- 2番目のステップでは、以前に見つかったレイアウト名とコンテキストモジュールに従って、実際のレイアウトファイルを決定します。レイアウト名は次のいずれかです。
- パスエイリアス (例: "@app/views/layouts/main")
- 絶対パス (例: "/main"): レイアウト名がスラッシュで始まる場合。実際のレイアウトファイルは、アプリケーションのレイアウトパスの下で検索されます。
- 相対パス (例: "main"): 実際のレイアウトファイルは、コンテキストモジュールのレイアウトパスの下で検索されます。
レイアウト名にファイル拡張子が含まれていない場合は、デフォルトの.php
が使用されます。
public string render ( $view, $params = [] ) | ||
$view | string |
ビュー名。 |
$params | array |
ビューで使用可能にする必要があるパラメータ(名前と値のペア)。これらのパラメータはレイアウトでは使用できません。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
ビューファイルまたはレイアウトファイルが存在しない場合。 |
public function render($view, $params = [])
{
$content = $this->getView()->render($view, $params, $this);
return $this->renderContent($content);
}
定義元: yii\base\Controller::renderContent()
レイアウトを適用して静的文字列をレンダリングします。
public string renderContent ( $content ) | ||
$content | string |
レンダリングされる静的文字列 |
return | string |
指定された静的文字列を |
---|
public function renderContent($content)
{
$layoutFile = $this->findLayoutFile($this->getView());
if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
}
return $content;
}
定義元: yii\base\Controller::renderFile()
ビューファイルをレンダリングします。
public string renderFile ( $file, $params = [] ) | ||
$file | string |
レンダリングするビューファイル。これは、ファイルパスまたはパスエイリアスのいずれかになります。 |
$params | array |
ビューで使用可能にする必要があるパラメータ(名前と値のペア)。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
ビューファイルが存在しない場合。 |
public function renderFile($file, $params = [])
{
return $this->getView()->renderFile($file, $params, $this);
}
定義元: yii\base\Controller::renderPartial()
レイアウトを適用せずにビューをレンダリングします。
このメソッドは、レイアウトを適用しないという点で、render()とは異なります。
public string renderPartial ( $view, $params = [] ) | ||
$view | string |
ビュー名。ビュー名の指定方法については、render()を参照してください。 |
$params | array |
ビューで使用可能にする必要があるパラメータ(名前と値のペア)。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
ビューファイルが存在しない場合。 |
public function renderPartial($view, $params = [])
{
return $this->getView()->render($view, $params, $this);
}
定義元: yii\base\Controller::run()
ルートで指定されたリクエストを実行します。
ルートは、このコントローラ内のアクションのID、またはモジュールID、コントローラID、およびアクションIDで構成される完全なルートのいずれかになります。ルートがスラッシュ'/'で始まる場合、ルートの解析はアプリケーションから開始されます。それ以外の場合は、このコントローラの親モジュールから開始されます。
runAction()も参照してください。
public mixed run ( $route, $params = [] ) | ||
$route | string |
処理するルート(例: 'view'、'comment/view'、'/admin/comment/view')。 |
$params | array |
アクションに渡されるパラメータ。 |
return | mixed |
アクションの結果。 |
---|
public function run($route, $params = [])
{
$pos = strpos($route, '/');
if ($pos === false) {
return $this->runAction($route, $params);
} elseif ($pos > 0) {
return $this->module->runAction($route, $params);
}
return Yii::$app->runAction(ltrim($route, '/'), $params);
}
定義元: yii\console\Controller::runAction()
指定されたアクションIDとパラメータでアクションを実行します。
アクションIDが空の場合、このメソッドは$defaultActionを使用します。
createAction()も参照してください。
public integer runAction ( $id, $params = [] ) | ||
$id | string |
実行するアクションのID。 |
$params | array |
アクションに渡されるパラメータ(名前と値のペア)。 |
return | integer |
アクション実行の状態。0 は正常、それ以外の値は異常を意味します。 |
---|---|---|
throws | yii\base\InvalidRouteException |
リクエストされたアクションIDがアクションとして正常に解決できない場合。 |
throws | yii\console\Exception |
不明なオプションまたは不足している引数がある場合 |
public function runAction($id, $params = [])
{
if (!empty($params)) {
// populate options here so that they are available in beforeAction().
$options = $this->options($id === '' ? $this->defaultAction : $id);
if (isset($params['_aliases'])) {
$optionAliases = $this->optionAliases();
foreach ($params['_aliases'] as $name => $value) {
if (array_key_exists($name, $optionAliases)) {
$params[$optionAliases[$name]] = $value;
} else {
$message = Yii::t('yii', 'Unknown alias: -{name}', ['name' => $name]);
if (!empty($optionAliases)) {
$aliasesAvailable = [];
foreach ($optionAliases as $alias => $option) {
$aliasesAvailable[] = '-' . $alias . ' (--' . $option . ')';
}
$message .= '. ' . Yii::t('yii', 'Aliases available: {aliases}', [
'aliases' => implode(', ', $aliasesAvailable)
]);
}
throw new Exception($message);
}
}
unset($params['_aliases']);
}
foreach ($params as $name => $value) {
// Allow camelCase options to be entered in kebab-case
if (!in_array($name, $options, true) && strpos($name, '-') !== false) {
$kebabName = $name;
$altName = lcfirst(Inflector::id2camel($kebabName));
if (in_array($altName, $options, true)) {
$name = $altName;
}
}
if (in_array($name, $options, true)) {
$default = $this->$name;
if (is_array($default) && is_string($value)) {
$this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
} elseif ($default !== null) {
settype($value, gettype($default));
$this->$name = $value;
} else {
$this->$name = $value;
}
$this->_passedOptions[] = $name;
unset($params[$name]);
if (isset($kebabName)) {
unset($params[$kebabName]);
}
} elseif (!is_int($name)) {
$message = Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]);
if (!empty($options)) {
$message .= '. ' . Yii::t('yii', 'Options available: {options}', ['options' => '--' . implode(', --', $options)]);
}
throw new Exception($message);
}
}
}
if ($this->help) {
$route = $this->getUniqueId() . '/' . $id;
return Yii::$app->runAction('help', [$route]);
}
return parent::runAction($id, $params);
}
定義元: yii\console\Controller::select()
ユーザーに選択肢を選択するオプションを提供します。入力として「?」を与えると、選択肢のリストとその説明が表示されます。
public string select ( $prompt, $options = [], $default = null ) | ||
$prompt | string |
プロンプトメッセージ |
$options | array |
選択肢となるオプションのキーと値の配列 |
$default | string|null |
ユーザーがオプションを選択しなかった場合に使う値。デフォルトが |
return | string |
ユーザーが選択したオプションの文字 |
---|
バージョン | 説明 |
---|---|
2.0.49 | $default 引数が追加されました |
public function select($prompt, $options = [], $default = null)
{
if ($this->interactive) {
return Console::select($prompt, $options, $default);
}
return $default;
}
定義元: yii\base\Controller::setView()
このコントローラーで使用されるビューオブジェクトを設定します。
public void setView ( $view ) | ||
$view | yii\base\View|yii\web\View |
ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクト。 |
public function setView($view)
{
$this->_view = $view;
}
定義元: yii\base\Controller::setViewPath()
ビューファイルが含まれるディレクトリを設定します。
public void setViewPath ( $path ) | ||
$path | string |
ビューファイルのルートディレクトリ。 |
throws | yii\base\InvalidArgumentException |
ディレクトリが無効な場合 |
---|
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
フィールドをチャンクに分割します
protected string[]|false splitFieldIntoChunks ( $field ) | ||
$field | string |
protected function splitFieldIntoChunks($field)
{
$originalDefaultValue = null;
$defaultValue = null;
preg_match_all('/defaultValue\(["\'].*?:?.*?["\']\)/', $field, $matches, PREG_SET_ORDER, 0);
if (isset($matches[0][0])) {
$originalDefaultValue = $matches[0][0];
$defaultValue = str_replace(':', '{{colon}}', $originalDefaultValue);
$field = str_replace($originalDefaultValue, $defaultValue, $field);
}
$chunks = preg_split('/\s?:\s?/', $field);
if (is_array($chunks) && $defaultValue !== null && $originalDefaultValue !== null) {
foreach ($chunks as $key => $chunk) {
$chunks[$key] = str_replace($defaultValue, $originalDefaultValue, $chunk);
}
}
return $chunks;
}
定義元: yii\console\Controller::stderr()
STDERRに文字列を出力します。
オプションで、yii\helpers\Console で定義されている定数を使用して追加のパラメータを渡すことで、ANSIコードで文字列をフォーマットできます。
例
$this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stderr ( $string ) | ||
$string | string |
出力する文字列 |
return | integer|boolean |
出力されたバイト数、エラーの場合はfalse |
---|
public function stderr($string)
{
if ($this->isColorEnabled(\STDERR)) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return fwrite(\STDERR, $string);
}
定義元: yii\console\Controller::stdout()
STDOUTに文字列を出力します。
オプションで、yii\helpers\Console で定義されている定数を使用して追加のパラメータを渡すことで、ANSIコードで文字列をフォーマットできます。
例
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stdout ( $string ) | ||
$string | string |
出力する文字列 |
return | integer|boolean |
出力されたバイト数、エラーの場合はfalse |
---|
public function stdout($string)
{
if ($this->isColorEnabled()) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return Console::stdout($string);
}
定義元: yii\base\Component::trigger()
イベントをトリガーします。
このメソッドはイベントの発生を表します。クラスレベルのハンドラを含む、イベントにアタッチされたすべてのハンドラを呼び出します。
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
イベント名 |
$event | yii\base\Event|null |
イベントのインスタンス。設定されていない場合、デフォルトのyii\base\Eventオブジェクトが作成されます。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
データベースを切り捨てます。
このメソッドは、データベースをクリアするタスクを実装するために、サブクラスでオーバーライドする必要があります。
protected void truncateDatabase ( ) | ||
throws | yii\base\NotSupportedException |
オーバーライドされていない場合 |
---|
protected function truncateDatabase()
{
$db = $this->db;
$schemas = $db->schema->getTableSchemas();
// First drop all foreign keys,
foreach ($schemas as $schema) {
foreach ($schema->foreignKeys as $name => $foreignKey) {
$db->createCommand()->dropForeignKey($name, $schema->name)->execute();
$this->stdout("Foreign key $name dropped.\n");
}
}
// Then drop the tables:
foreach ($schemas as $schema) {
try {
$db->createCommand()->dropTable($schema->name)->execute();
$this->stdout("Table {$schema->name} dropped.\n");
} catch (\Exception $e) {
if ($this->isViewRelated($e->getMessage())) {
$db->createCommand()->dropView($schema->name)->execute();
$this->stdout("View {$schema->name} dropped.\n");
} else {
$this->stdout("Cannot drop {$schema->name} Table .\n");
}
}
}
}
コメントするにはサインアップまたはログインしてください。