将 TINYINT 添加到 Doctrine SQL 类型

Add TINYINT to Doctrine SQL types

根据 Symfony 文档,我尝试添加 TINYINT 作为实体列类型。

到目前为止它运行良好,但仍然存在两个问题...

  1. 每次我想执行迁移时,Doctrine 都无法为关联的列重新整理TINYINT,并再次执行迁移查询。

  2. 在表单构建器中,默认情况下 TINYINT 被重新识别为 TextType 而不是 NumberType

你知道我缺少什么来解决这两个问题吗?

TinyintType.php

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

class TinyintType extends Type {
    const TINYINT='tinyint';

    /**
     * @return string
     */
    public function getName() {
        return self::TINYINT;
    }

    /**
     * @param array $fieldDeclaration
     * @param AbstractPlatform $platform
     * @return string
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) {
        return $fieldDeclaration['unsigned'] === true ? 'TINYINT(1) UNSIGNED' : 'TINYINT(1)';
    }

    public function canRequireSQLConversion() {
        return true;
    }

    /**
     * @param $value
     * @param AbstractPlatform $platform
     * @return int|null
     */
    public function convertToPHPValue($value, AbstractPlatform $platform) {
        return $value === null ? null : (int)$value;
    }

    /**
     * @param mixed $value
     * @param AbstractPlatform $platform
     * @return int|mixed|null
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform) {
        return $value === null ? null : (int)$value;
    }

    /**
     * @return int
     */
    public function getBindingType() {
        return ParameterType::INTEGER;
    }
}

doctrine.yaml

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
        server_version: '5.7'
        types:
            tinyint: 'App\Doctrine\DBAL\Types\TinyintType'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

第一期:来自https://blog.vandenbrand.org/2015/06/25/creating-a-custom-doctrine-dbal-type-the-right-way/

The solution is to add a comment to the field to store the metadata in. This seems to be missing in the docs but I’ve found some JIRA issue describing the feature. We have to change our column definition so the metadata of the type doesn’t get lost

所以你的 getSQLDeclaration 应该是这样的:

public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
    return 'TINYINT'.(!empty($fieldDeclaration['unsigned']) ? ' UNSIGNED' : '').' COMMENT \'(DC2Type:tinyint)\'';
}

第二期:那是因为symfony表单默认使用文本类型(symfony/form/FormBuilder.php::create)

if (null === $type && null === $this->getDataClass()) {
    $type = 'Symfony\Component\Form\Extension\Core\Type\TextType';
}

如果您想设置其他类型,您应该明确设置您的类型。