0

Using SF 2.8 and serializer component.

I have 2 entities with relationships many to one.

ENTITY USUARIO

...
class Usuario implements UserInterface
{
...
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var string
 *
 * @ORM\Column(name="nombre", type="string", length=50)
 */
private $nombre;

/**
 * @var string
 *
 * @ORM\Column(name="apellidos", type="string", length=100)
 */
private $apellidos;

...getters and setters...

ENTITY PLAN

...
class Plan
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="\UsuariosBundle\Entity\Usuario", cascade={"persist"})
 * @ORM\JoinColumn(name="usuario_id", referencedColumnName="id", onDelete="CASCADE")
 */
private $usuario;

/**
 * @var array
 *
 * @ORM\Column(name="json_dieta", type="json_array")
 */
private $jsonDieta;

...getters and setters...   

As you can see, property $usuario (entity plan) is joined with $id (entity usuario).

My intention is to save a json in a field of the table plan of the DB to recover the data when I need them; for do that, first I have to serialize the data and save the to the DB (DONE!) but when I have to deserialize them for recovering the data and transform them to objects I get this error:

Type error: Argument 1 passed to ComponentesBundle\Entity\Receta::setUsuario() must be an instance of UsuariosBundle\Entity\Usuario, array given, called in C:\xampp7\htdocs\Dietas\vendor\symfony\serializer\Normalizer\GetSetMethodNormalizer.php on line 118

MY CONTROLLER

...
$em = $this->getDoctrine()->getManager();

    $plan =$em->getRepository('UsuariosBundle:Plan')->findOneByUsuario($user->getId());

    $serializer = new Serializer(
        array(new GetSetMethodNormalizer(), new ArrayDenormalizer()),
        array(new JsonEncoder())
        );
    $jsonDeserializado = $serializer->deserialize($plan->getJsonDieta(), 'ComponentesBundle\Entity\Receta[][][]', 'json');
    dump($jsonDeserializado);
...

Any idea how can I solve this?

1 Answers1

0

First you can view here how to should be looks like correct entity and mapping for one to many bidirectional: Relationships in Doctrine And after that you use serializer anotation strategy inside entity or you can create mapping strategy for serializer what propery to serialize and which does not

l13
  • 529
  • 3
  • 11
  • thanks for your response; in this case I use unidirectional relationship and I have checked it and I think it is OK; Using annotation for groups could be a solution if I would want avoid to serialize or deserialize the conflictive property but I need to convert the complete json like the entire object – viejalospelos Apr 10 '18 at 14:29
  • Okey, I uderstand, But I will recommend you to use http://jmsyst.com/bundles/JMSSerializerBundle – l13 Apr 10 '18 at 16:43