RyukShi
RyukShi

Reputation: 93

Quick PHP question about JSON encode doctrine in Symfony

I have a question about an attribute in my entity (Recipe.php), the ingredients array attribute is a JSON type in my table. There is a JSON ecode of this array and does the type matter for JSON encoding? For example, if I choose the collection type for the ingredients. Could this work? for the encoding process with ORM and Doctrine. Thanks for your help !

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

Upvotes: 0

Views: 190

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52493

You will need to register a Doctrine custom type to serialize/deserialize the JSON database field to a collection object.

Example:

<?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
    }
}

Then register your custom type in your Symfony configuration for the DoctrineBundle.

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

Upvotes: 1

Related Questions