Buscar..


Creando Migraciones

yii migrate/create <name>

El argumento del nombre requerido proporciona una breve descripción de la nueva migración. Por ejemplo, si la migración se trata de crear una nueva tabla llamada noticias, puede usar el nombre create_news_table y ejecutar el siguiente comando

yii migrate/create create_news_table

Ejemplo de archivo de migración

<?php

use yii\db\Migration;

class m150101_185401_create_news_table extends Migration
{
public function up()
{

}

public function down()
{
    echo "m101129_185401_create_news_table cannot be reverted.\n";

    return false;
}

/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}

public function safeDown()
{
}
*/
}

Mesa plegable

public function up()
{
    $this->dropTable('post');
}

Crear campos de tabla de inmediato

yii migrate/create create_post_table --fields="title:string,body:text"

Genera:

/**
 * Handles the creation for table `post`.
 */
class m150811_220037_create_post_table extends Migration
{
/**
 * @inheritdoc
 */
public function up()
{
    $this->createTable('post', [
        'id' => $this->primaryKey(),
        'title' => $this->string(),
        'body' => $this->text(),
    ]);
}

/**
 * @inheritdoc
 */
public function down()
{
    $this->dropTable('post');
}
}

Crear mesa

public function up()
{
    $this->createTable('post', [
        'id' => $this->primaryKey()
    ]);
}

Drop / Rename / Alter Column

public function up()
{
    $this->dropColumn('post', 'position');

    $this->renameColumn('post', 'owner_id', 'user_id');

    $this->alterColumn('post', 'updated', $this->timestamp()->notNull()->defaultValue('0000-00-00 00:00:00'));
}

Añadir columna

public function up()
{
    $this->addColumn('post', 'position', $this->integer());
}

Revertir las migraciones

yii migrate/down     # revert the most recently applied migration
yii migrate/down 3   # revert the most 3 recently applied migrations

Migraciones transaccionales

public function safeUp()
{
    $this->createTable('news', [
        'id' => $this->primaryKey(),
        'title' => $this->string()->notNull(),
        'content' => $this->text(),
    ]);

    $this->insert('news', [
        'title' => 'test 1',
        'content' => 'content 1',
    ]);
}

public function safeDown()
{
    $this->delete('news', ['id' => 1]);
    $this->dropTable('news');
}

Una forma aún más fácil de implementar migraciones transaccionales es colocar el código de migración en los safeUp() y safeDown() . Estos dos métodos difieren de up() y down() en que están encerrados implícitamente en una transacción. Como resultado, si falla alguna operación en estos métodos, todas las operaciones anteriores se revertirán automáticamente.

Migración de múltiples bases de datos

De forma predeterminada, las migraciones se aplican a la misma base de datos especificada por el componente de la aplicación db. Si desea que se apliquen a una base de datos diferente, puede especificar la opción de línea de comandos db como se muestra a continuación:

yii migrate --db=db2

Rehacer migraciones

yii migrate/redo        # redo the last applied migration
yii migrate/redo 3      # redo the last 3 applied migrations

Listado de Migraciones

yii migrate/history     # showing the last 10 applied migrations
yii migrate/history 5   # showing the last 5 applied migrations
yii migrate/history all # showing all applied migrations

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

Modificar el historial de migración

yii migrate/mark 150101_185401                      # using timestamp to specify the migration
yii migrate/mark "2015-01-01 18:54:01"              # using a string that can be parsed by strtotime()
yii migrate/mark m150101_185401_create_news_table   # using full name
yii migrate/mark 1392853618                         # using UNIX timestamp

Aplicando Migraciones

yii migrate

Este comando mostrará una lista de todas las migraciones que no se han aplicado hasta el momento. Si confirma que desea aplicar estas migraciones, ejecutará el método up () o safeUp () en cada nueva clase de migración, una tras otra, en el orden de sus valores de marca de hora. Si falla alguna de las migraciones, el comando se cerrará sin aplicar el resto de las migraciones.

yii migrate 3
yii migrate/to 150101_185401                      # using timestamp to specify the migration
yii migrate/to "2015-01-01 18:54:01"              # using a string that can be parsed by strtotime()
yii migrate/to m150101_185401_create_news_table   # using full name
yii migrate/to 1392853618                         # using UNIX timestamp


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow