[英]Quick PHP question about JSON encode doctrine in Symfony
我對我的實體 (Recipe.php) 中的屬性有疑問,成分數組屬性是我表中的 JSON 類型。 這個數組有一個 JSON 編碼,JSON 編碼的類型是否重要? 例如,如果我選擇成分的集合類型。 這能行嗎? 用於 ORM 和 Doctrine 的編碼過程。 謝謝你的幫助 !
#[ORM\Column]
private array $ingredients = [];
您需要注冊一個 Doctrine 自定義類型來序列化/反序列化 JSON 數據庫字段到集合 object。
例子:
<?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
}
}
然后在 DoctrineBundle 的 Symfony 配置中注冊您的自定義類型。
doctrine:
dbal:
types:
my_type: My\Project\Types\MyType
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.