In Yii 2.0, based on database migration, implement the primary key of the string type
1. In Yii 2.0, create a primary key column based on database migration. $this->primaryKey() is used by default. The created primary key column is int(11) by default. as shown in Figure 1
2. Some colleagues plan to create a primary key column of type VARCHAR(32). as shown in Figure 2
3. Method primaryKey() only supports passing in a column-sized parameter. Therefore, the primary key of the string type cannot be implemented based on this method.
/**
* 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. In the end, it is decided to create a field of the string type first, and after the creation of the table is completed, set the field as the primary key (using the method addPrimaryKey()). Create a primary key on an existing field.
/**
* 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. The final code is implemented as follows. as shown in Figure 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');


