关于Symfony中JSON编码原则的PHP快速问题

lx0bsm1f  于 2022-11-16  发布在  PHP
关注(0)|答案(1)|浏览(143)

我有一个关于我的实体(Recipe.php)中的属性的问题,在我的表中,成分数组属性是JSON类型。这个数组有一个JSON代码,类型对JSON编码有影响吗?例如,如果我为成分选择集合类型。这可以工作吗?对于ORM和Doctrine的编码过程。谢谢你的帮助!

#[ORM\Column]
private array $ingredients = [];
9jyewag0

9jyewag01#

您需要注册一个Doctrine自定义类型,以便将JSON数据库字段序列化/反序列化为集合对象。
示例:

<?php
namespace My\Project\Types;

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

/**
 * My custom datatype.
 */
class MyType extends Type
{
    const MYTYPE = 'mytype'; // modify to match your type name

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        // return the SQL used to create your column type. To create a portable column type, use the $platform.
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        // This is executed when the value is read from the database. Make your conversions here, optionally using the $platform.
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        // This is executed when the value is written to the database. Make your conversions here, optionally using the $platform.
    }

    public function getName()
    {
        return self::MYTYPE; // modify to match your constant name
    }
}

然后在Symfony配置中为DoctrineBundle注册自定义类型。

doctrine:
  dbal:
    types:
      my_type:  My\Project\Types\MyType

相关问题