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

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

有同事计划创建一个主键列,其类型为 varchar(32)。
1、在 Yii 2.0 中,基于数据库迁移,创建一个主键列。默认使用 $this->primaryKey()。创建的主键列其类型默认为 int(11)。如图1
在 Yii 2.0 中,基于数据库迁移,创建一个主键列。默认使用 $this->primaryKey()。创建的主键列其类型默认为 int(11)。
图1
2、有同事计划创建一个主键列,其类型为 varchar(32)。如图2
有同事计划创建一个主键列,其类型为 varchar(32)。
图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');


PHP / Laravel / Yii2 老项目维护与长期技术支持

如果你的 PHP / Laravel / Yii2 项目已经上线,但遇到原开发离职、Bug 长期无人修复、接口不稳定、性能下降、代码难以接手等问题,可以联系我做一次远程技术排查。

适合以下情况:
✅ 老旧 PHP 系统无人维护
✅ Laravel / Yii2 项目 Bug 修复
✅ 后台管理系统小功能迭代
✅ RESTful API 接口排查
✅ MySQL / Redis / Nginx 性能问题
✅ 长期远程兼职维护

可先从一次小问题开始:
✅ 线上报错排查
✅ 接口异常分析
✅ 慢查询与性能瓶颈定位
✅ 代码结构初步评估
✅ 部署环境与日志检查

如需咨询,请联系我,并注明:PHP 维护咨询

联系方式:
Telegram:@shuijingwan
微信:13980074657
邮箱:shuijingwanwq@gmail.com

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理