[Doctrine Migrations] 數據庫遷移組件的深刻解析三:自定義數據字段類型

自定義type

根據官方文檔,新建TinyIntType類,集成Type,並重寫getNamegetSqlDeclarationconvertToPHPValuegetBindingType等方法。php

TinyIntType.php完整代碼:html

<?php
namespace db\types;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
/**
 * 擴展DBAL組件類型
 *
 * 遷移組件依賴的DBAL組件默認並不支持tinyint類型
 * 此類是爲mysql支持tinyint類型而擴展的類
 *
 * @author tangbo<admin@tbphp.net>
 */
class TinyIntType extends Type
{
    public function getName()
    {
        return 'tinyint';
    }
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $sql = 'TINYINT';
        if (is_numeric($fieldDeclaration['length']) && $fieldDeclaration['length'] > 1) {
            $sql .= '(' . ((int) $fieldDeclaration['length']) . ')';
        } else {
            $sql .= '(3)';
        }
        if (!empty($fieldDeclaration['unsigned'])) {
            $sql .= ' UNSIGNED';
        }
        if (!empty($fieldDeclaration['autoincrement'])) {
            $sql .= ' AUTO_INCREMENT';
        }
        return $sql;
    }
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return (null === $value) ? null : (int) $value;
    }
    public function getBindingType()
    {
        return ParameterType::INTEGER;
    }
}

其中getSqlDeclaration方法是用於生成sql語句,須要根據傳入的參數處理sql拼接。mysql

註冊自定義類型

Type::addType(TinyIntType::TYPENAME, 'db\types\TinyIntType');
$connection->getDatabasePlatform()->registerDoctrineTypeMapping(TinyIntType::TYPENAME, TinyIntType::TYPENAME);

這樣,你在編寫遷移類代碼的時候就能夠使用tinyint了,例如:laravel

public function up(Schema $schema): void
{
    $table = $schema->createTable('test1');
    $table->addColumn('id', 'integer')->setUnsigned(true)->setAutoincrement(true);
    $table->addColumn('status', 'tinyint')->setLength(2)->setDefault(1);
    $table->setPrimaryKey(['id']);
}

解決enum類型衝突

遷移組件不支持enum類型,也沒法自定義該類型。若是集成遷移組件的時候數據庫裏已經存在表且有enum類型的字段,那麼執行遷移命令時就會報錯。git

爲了解決這個問題,咱們須要把enum映射爲string類型便可:github

$connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

結語

至此,咱們已經完成了遷移組件的全部遷移工做,而且已經能很好的在項目中使用它。sql

目前集成的是版本管理的方式,是遷移組件默認支持的,也是laravel框架集成的遷移方式。還有以前說到的另外一種diff方式的遷移,diff方式可以更精準的控制表結構。數據庫

下一章咱們來詳細研究如何集成diff方式的數據遷移組件。app

個人代碼庫能夠查看這篇文章的詳細代碼,歡迎star。
相關文章
相關標籤/搜索