没有不值得去解决的问题,也没有不值得去学习的技术!

Best Practices for Adding Four Fields in a New Yii 2.0 Database Migration

Add fields. If the migration name follows the format add_xxx_to_yyy, the generated class file will contain the necessary addColumn and dropColumn. You can specify multiple fields like this: yii migrate/create add_xxx_column_yyy_column_to_zzz_table --fields="xxx:integer,yyy:text".

1. Table name: cpa_channel_app_source design, table prefix: cpa_, as shown in Figure 1

Table name: cpa_channel_app_source design, table prefix: cpa_
Figure 1

2. View the help documentation for the command: yii migrate/create

Plaintext

PS E:\wwwroot\channel-pub-api> ./yii help migrate/create

DESCRIPTION
                    "
Creates a new migration.

This command creates a new migration using the available migration template.
After using this command, developers should modify the created migration
skeleton by filling up the actual migration logic.

yii migrate/create create_user_table

In order to generate a namespaced migration, you should specify a namespace before the migration's name.
Note that backslash (\) is usually considered a special character in the shell, so you need to escape it
properly to avoid shell errors or incorrect behavior.
For example:

yii migrate/create 'app\\migrations\\createUserTable'

In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.


USAGE

yii migrate/create  [...options...]

- name (required): string
  the name of the new migration. This should only contain
  letters, digits, underscores and/or backslashes.

  Note: If the migration name is of a special form, for example create_xxx or
  drop_xxx, then the generated migration file will contain extra code,
  in this case for creating/dropping tables.


OPTIONS

--appconfig: string
  custom application configuration file path.
  If not set, default application configuration is used.

--color: boolean, 0 or 1
  whether to enable ANSI color in the output.
  If not set, ANSI color will only be enabled for terminals that support it.

--comment, -C: string (defaults to '')
  the comment for the table being created.

--compact, -c: boolean, 0 or 1 (defaults to 0)
  indicates whether the console output should be compacted.
  If this is set to true, the individual commands ran within the migration will not be output to the console.
  Default is false, in other words the output is fully verbose by default.

--db: Connection|array|string (defaults to 'db')
  the DB connection object or the application component ID of the DB connection to use
  when applying migrations. Starting from version 2.0.3, this can also be a configuration array
  for creating the object.

--fields, -f: array
  column definition strings used for creating migration code.

  The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
  For example, `--fields="name:string(12):notNull:unique"`
  produces a string column of size 12 which is not null and unique values.

  Note: primary key is added automatically and is named id by default.
  If you want to use another name you may specify it explicitly like
  `--fields="id_key:primaryKey,name:string(12):notNull:unique"`

--help, -h: boolean, 0 or 1
  whether to display help information about current command.

--interactive: boolean, 0 or 1 (defaults to 1)
  whether to run the command interactively.

--migration-namespaces: array
  list of namespaces containing the migration classes.

  Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify
  the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return
  the file path to the directory this namespace refers to.
  This corresponds with the [autoloading conventions](guide:concept-autoloading) of Yii.

  For example:

  ```php
  [
      'app\migrations',
      'some\extension\migrations',
  ]
  ```

--migration-path, -p: string|array
  the directory containing the migration classes. This can be either
  a [path alias](guide:concept-aliases) or a directory path.

  Migration classes located at this path should be declared without a namespace.
  Use [[migrationNamespaces]] property in case you are using namespaced migrations.

  If you have set up [[migrationNamespaces]], you may set this field to `null` in order
  to disable usage of migrations that are not namespaced.

  Since version 2.0.12 you may also specify an array of migration paths that should be searched for
  migrations to load. This is mainly useful to support old extensions that provide migrations
  without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations.

  In general, to load migrations from different locations, [[migrationNamespaces]] is the preferable solution
  as the migration name contains the origin of the migration in the history, which is not the case when
  using multiple migration paths.

--migration-table, -t: string (defaults to '{{%migration}}')
  the name of the table for keeping applied migration information.

--template-file, -F:  (defaults to '@yii/views/migration.php')

--use-table-prefix, -P: boolean, 0 or 1 (defaults to 1)
  indicates whether the table names generated should consider
  the `tablePrefix` setting of the DB connection. For example, if the table
  name is `post` the generator wil return `{{%post}}`.


3. Add fields. If the migration name follows the format add_xxx_to_yyy, the generated class file will contain the necessary addColumn and dropColumn. You can specify multiple fields like this: yii migrate/create add_xxx_column_yyy_column_to_zzz_table –fields=”xxx:integer,yyy:text”. As shown in Figure 2

Add fields. If the migration name follows the format add_xxx_to_yyy, the generated class file will contain the necessary addColumn and dropColumn. You can specify multiple fields like this: yii migrate/create add_xxx_column_yyy_column_to_zzz_table --fields="xxx:integer,yyy:text".
Figure 2
Plaintext

PS E:\wwwroot\channel-pub-api> ./yii migrate/create add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table --fields="group_name:string(64):notNull:defaultValue(''),name:string(32):notNull:defaultValue(''),avatar:string:notNull:defaultValue(''),fans_count:integer:notNull:defaultValue(0)"
Yii Migration Tool (based on Yii v2.0.35)

Create new migration 'E:\wwwroot\channel-pub-api\console/migrations\m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table.php'? (yes|no) [no]:yes
New migration created successfully.

4. Generate the PHP class file: m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table.php.

PHP
<?php
 
use yii\db\Migration;
 
/**
 * Handles adding columns to table `{{%channel_app_source}}`.
 */
class m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->addColumn('{{%channel_app_source}}', 'group_name', $this->string(64)->notNull()->defaultValue(''));
        $this->addColumn('{{%channel_app_source}}', 'name', $this->string(32)->notNull()->defaultValue(''));
        $this->addColumn('{{%channel_app_source}}', 'avatar', $this->string()->notNull()->defaultValue(''));
        $this->addColumn('{{%channel_app_source}}', 'fans_count', $this->integer()->notNull()->defaultValue(0));
    }
 
    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropColumn('{{%channel_app_source}}', 'group_name');
        $this->dropColumn('{{%channel_app_source}}', 'name');
        $this->dropColumn('{{%channel_app_source}}', 'avatar');
        $this->dropColumn('{{%channel_app_source}}', 'fans_count');
    }
}

5. Edit the PHP class file: m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table.php. To add other field options: field comments, field order.

PHP
<?php
 
use yii\db\Migration;
 
/**
 * Handles adding columns to table `{{%channel_app_source}}`.
 */
class m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->addColumn('{{%channel_app_source}}', 'group_name', $this->string(64)->notNull()->defaultValue('')->comment('租户名称')->after('group_id'));
        $this->addColumn('{{%channel_app_source}}', 'name', $this->string(32)->notNull()->defaultValue('')->comment('名称')->after('channel_type_code'));
        $this->addColumn('{{%channel_app_source}}', 'avatar', $this->string()->notNull()->defaultValue('')->comment('头像')->after('name'));
        $this->addColumn('{{%channel_app_source}}', 'fans_count', $this->integer()->notNull()->defaultValue(0)->comment('粉丝数')->after('avatar'));
    }
 
    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropColumn('{{%channel_app_source}}', 'group_name');
        $this->dropColumn('{{%channel_app_source}}', 'name');
        $this->dropColumn('{{%channel_app_source}}', 'avatar');
        $this->dropColumn('{{%channel_app_source}}', 'fans_count');
    }
}

6. Apply the migration. To upgrade the database to the latest structure, you should use the following command to apply all new migrations. As shown in Figure 3

Apply the migration. To upgrade the database to the latest structure, you should use the following command to apply all new migrations.
Figure 3
Plaintext
PS E:\wwwroot\channel-pub-api> ./yii migrate
Yii Migration Tool (based on Yii v2.0.35)

Total 1 new migration to be applied:
        m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table

Apply the above migration? (yes|no) [no]:yes
*** applying m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table
    > add column group_name string(64) NOT NULL DEFAULT '' COMMENT '租户名称' AFTER `group_id` to table {{%channel_app_source}} ... done (time: 0.108s)
    > add column name string(32) NOT NULL DEFAULT '' COMMENT '名称' AFTER `channel_type_code` to table {{%channel_app_source}} ... done (time: 0.097s)
    > add column avatar string NOT NULL DEFAULT '' COMMENT '头像' AFTER `name` to table {{%channel_app_source}} ... done (time: 0.170s)
    > add column fans_count integer NOT NULL DEFAULT 0 COMMENT '粉丝数' AFTER `avatar` to table {{%channel_app_source}} ... done (time: 0.158s)
*** applied m201014_055436_add_group_name_column_name_column_avatar_column_fans_count_column_to_channel_app_source_table (time: 0.551s)


1 migration was applied.

Migrated up successfully.

7. View the latest table design, which meets expectations, as shown in Figure 4

View the latest table design, which meets expectations
Figure 4

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系