【发布时间】:2022-09-24 00:19:29
【问题描述】:
我对我的实体 (Recipe.php) 中的属性有疑问,成分数组属性是我表中的 JSON 类型。这个数组有一个 JSON 编码,JSON 编码的类型重要吗?例如,如果我选择成分的集合类型。这能行吗?用于 ORM 和 Doctrine 的编码过程。谢谢你的帮助 !
#[ORM\\Column]
private array $ingredients = [];
我对我的实体 (Recipe.php) 中的属性有疑问,成分数组属性是我表中的 JSON 类型。这个数组有一个 JSON 编码,JSON 编码的类型重要吗?例如,如果我选择成分的集合类型。这能行吗?用于 ORM 和 Doctrine 的编码过程。谢谢你的帮助 !
#[ORM\\Column]
private array $ingredients = [];
您需要注册一个 Doctrine custom type 以将 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
【讨论】: