0

I'm persisting a field of type ArrayCollection to a MySQL database which contains only stings. The database field is of type "array" in the ORM definition and of type TEXT in the database.

/**
 * @var ArrayCollection
 *
 * @ORM\Column(name="currencies", type="array")
 */
private $currencies;

When persisted it looks like this in the database:

O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:54:"Doctrine\Common\Collections\ArrayCollection_elements";a:3:{i:0;s:3:"EUR";i:1;s:3:"USD";i:2;s:3:"GBP";}}

Is there a way to get something more close to a json array into the database? Something like this:

['EUR', 'USD', 'GBP']
Christian Kolb
  • 1,368
  • 2
  • 23
  • 43

2 Answers2

1

Why are you setting an ArrayCollection to your $currencies property ? Why don't you use an array ?

You may also use the "json_array" Doctrine type instead of "array".

Yann Eugoné
  • 1,311
  • 1
  • 8
  • 17
0

Doctrine uses the PHP function serialize() when inserting into the database.

Upon fetching, it uses deserialize().

You can simply use: echo json_encode($entity->getCurrencies());.

See also this question: How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

Community
  • 1
  • 1
Daniel W.
  • 31,164
  • 13
  • 93
  • 151