Search code examples
phpsymfonydoctrine-ormarraycollection

Doctrine doesn't store ArrayCollection


I have an Entity that has a array field like this:

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

I fill this using form and it fills correctly as after submit var_dump($entity->getTels()) returns this:

object(Doctrine\Common\Collections\ArrayCollection)[448]
  private '_elements' => 
    array (size=1)
      0 => string '123' (length=3)

But after persist doctrine ignores this fields value and stores empty array:

+----+------+
| id | tels |
+----+------+
|  1 | {}   |
+----+------+

What is the problem?


Solution

  • The type json_array expects an array which will then be converted to json using json_encode. While a Doctrine ArrayCollection is technically traversable it doesnt nicely cast to array. So you either need to call ->toArray() on it or change your type to just be array

    $entity->setTels($theArrayCollection->toArray());