将TINYINT添加到Doctrine SQL类型

问题描述

在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/

解决方案是在字段中添加注释以存储元数据 进入。文档中似乎缺少此功能,但我发现了一些JIRA 问题描述功能。我们必须更改列定义 这样类型的元数据就不会丢失

因此您的 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';
}

如果要设置其他类型,则应明确设置类型。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...