gpt4 book ai didi

php - 使用Doctrine2进行SELECT时如何自动将mysql的SET转换为其整数?

转载 作者:行者123 更新时间:2023-11-29 08:10:28 24 4
gpt4 key购买 nike

mysql's SET data type通常用于表示可以使用按位运算组合选项的选项。

例如。

    SELECT set_column, set_column + 0 FROM table
  • 第一个将返回以逗号分隔的选项列表(例如“option1, option2”)
  • 第二个将返回 3 (1+2)

我正在使用 Doctrine2,并且仅处理对象(不使用部分对象或数组)。所以我的问题是如何在查询实体的存储库时检索第二种格式?

如果我将列映射为字符串,它将返回第一种格式。如果映射到整数,php 将转换为 0 (intval('options, ...'))。

一个肮脏的黑客会将其添加到映射属性中:

    @ORM\Column(name="set_column+0", type="integer")

...但是在插入或更新时会导致问题。

有什么想法吗?

最佳答案

您需要为 Doctrine 创建自定义类型,因为它不提供对 SET 类型的内置支持。幸运的是,这很简单:

  1. 定义类型类:

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

    class MyCustomSetType extends Type
    {
    const TYPE = 'my_custom_set';

    private $possibleValues = array('option1', 'opton2', ..., 'optionN');

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
    return sprintf("SET('%s')", implode(',', $this->possibleValues));
    }

    public function convertToPHPValue($values, AbstractPlatform $platform)
    {
    return explode(',', $values);
    }

    public function convertToDatabaseValue($values, AbstractPlatform $platform)
    {
    if (!is_array($values)) {
    throw new \InvalidArgumentException('...');
    }

    foreach ($values as $value) {
    if (!in_array($value, $this->possibleValues, true)) {
    throw new \InvalidArgumentException('...');
    }
    }


    return implode(',', $values);
    }

    public function getName()
    {
    return self::TYPE;
    }
    }
  2. 注册您新创建的类型:

    \Doctrine\DBAL\Types\Type::addType('my_custom_set', '\My\Type\MyCustomSet');
  3. 为您的实体定义适当的映射:

    /**
    * @ORM\Column(type="my_custom_set")
    */
    protected $options = array();

如果您想了解有关自定义类型的更多信息,请阅读文档:Custom Mapping Types

关于php - 使用Doctrine2进行SELECT时如何自动将mysql的SET转换为其整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21727319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com