1

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

3
  • $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 :) Commented Apr 10, 2018 at 4:04
  • Possible duplicate of : stackoverflow.com/questions/23051554/… Commented Apr 10, 2018 at 6: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? Commented Apr 10, 2018 at 7:37

1 Answer 1

1

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

example:

$house = $serializer->deserialize($json, House::class, 'json');
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.