0

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 = [];
0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.