在 Yii 2.0 中,基于数据库迁移,实现字符串类型的主键

1、在 Yii 2.0 中,基于数据库迁移,创建一个主键列。默认使用 $this->primaryKey()。创建的主键列其类型默认为 int(11)。如图1

图1

2、有同事计划创建一个主键列,其类型为 varchar(32)。如图2

图2

3、方法 primaryKey() 仅支持传入一个列大小的参数。因此,无法基于此方法实现字符串类型的主键。

    /**
     * Creates a primary key column.
     * @param int $length column size or precision definition.
     * This parameter will be ignored if not supported by the DBMS.
     * @return ColumnSchemaBuilder the column instance which can be further customized.
     * @since 2.0.6
     */    public function primaryKey($length = null)
    {
        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length);
    }

4、最后决定先创建一个字符串类型的字段,创建表完成后,再设置字段为主键(使用方法 addPrimaryKey())。在已经存在的字段上创建主键。

    /**
     * Builds and executes a SQL statement for creating a primary key.
     * The method will properly quote the table and column names.
     * @param string $name the name of the primary key constraint.
     * @param string $table the table that the primary key constraint will be added to.
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
     */    public function addPrimaryKey($name, $table, $columns)
    {
        $time = $this->beginCommand("add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ')');
        $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
        $this->endCommand($time);
    }

5、最终代码实现如下。如图3

图3

        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB COMMENT="渠道"';
        };
        $this->createTable('{{%ccp_platform_account}}', [
            'account_uuid' => $this->string(32)->notNull(),
        ], $tableOptions);

        $this->addPrimaryKey('account_uuid','{{%ccp_platform_account}}','account_uuid');
永夜