0

How do I deserialize the photos collection in to a Photo entity using Symfony?

Here is my json:

{
    "id": 3,
    "status": 1,
    "title": "sometitle",
    "agency": {
        "id": 1,
        "name": "AgencyName",
        ...
        "created_at": "-0001-11-30T00:00:00+01:00",
        "updated_at": "-0001-11-30T00:00:00+01:00"
    },
    "price": "123123",
    ...
    "created_at": "-0001-11-30T00:00:00+01:00",
    "updated_at": "-0001-11-30T00:00:00+01:00",
    "photos": [
        {
            "id": 1,
            "path": "img1.jpg",
            "created_at": "2018-04-05T15:29:47+02:00",
            "updated_at": "2018-04-05T15:29:47+02:00"
        },
        {
            "id": 2,
            "path": "img2.jpg",
            "created_at": "2018-04-05T15:35:28+02:00",
            "updated_at": "2018-04-05T15:35:28+02:00"
        }
    ]
}

How do I specify in the Photo entity that it should use the collection as manytoone?

This is not working:

\Entity\Photo.php
/**
 * @ORM\ManyToOne(targetEntity="House", inversedBy="photos")
 */
private $house;

\Entity\House.php
/**
 * @ORM\OneToMany(targetEntity="Photo", mappedBy="house")
 */
private $photos;

When I call it in my view:

{% for photo in house.photos %}
    <li>{{ photo.path }}</li>
{% endfor %}

It is throwing an excepting and is trying to send another GET request toa different route in the API instead of just using the nested collection

Nodir Rashidov
  • 692
  • 9
  • 32
  • $stuff = json_decode($json, true); // true, to preserve assoc. $stuff['photos'][0]['path'] would be the first photo's path, so you would do something like... for photo in $stuff['photos'] I'm guessing if you json_decoded this. I am not great with Symphony, so I only know what to do with core PHP... Json decode & then access the values you want just like an assoc array :) – Nerdi.org Apr 10 '18 at 04:04
  • Possible duplicate of : https://stackoverflow.com/questions/23051554/symfony-deserialize-json-to-an-array-of-entities – Weenesta - Mathieu Dormeval Apr 10 '18 at 06:24
  • @MathieuDormeval not sure if it is. I want to build a web app that doesnt need to connect to mysql and only uses API requests to manage the data. So i went with DoctrineRestDriver. I might have to change to something else. Can you recommend anything? – Nodir Rashidov Apr 10 '18 at 07:37

1 Answers1

1

You can use Symfony Serializer Component: https://symfony.com/doc/3.4/components/serializer.html

example:

$house = $serializer->deserialize($json, House::class, 'json');
Youri_G
  • 219
  • 2
  • 9