简体   繁体   中英

Doctrine 2: Return related objects as array

I have a User entity, that has a many to many relation with a Tipo entity.

I have the method to retrieve the related entities already working, so assuming $u is my user, $u->getIdtipo() returns all the wanted related objects.

Now, the result of the function above is a collection, but i need an array, since i want to return it as a json to my call.

I tryed to apply the ->toArray() as well to the result of getIdtipo() , but the result of that operation is that it creates an array of Tipo objects, while i need an array of array.

Is possible to convert the collection of object returned by getIdtipo to a json, or an array of array?

Note: i would like to use the getIdtipo() instead of making a custom query to retrieve the same results.


answer

As from marked answer, i implemented a serializer, and used it.

From symfony documentation , i run composer require symfony/serializer

Than I created in my main controller a function that serialize, that's what i did:

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

public function serialize($data, $format){
    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new ObjectNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    return $serializer->serialize($data, $format);

}

and then simply return the user's tipo doing

$this->serialize($u->getIdtipo(), 'json'));

The easy way would be to implement JsonSerializable on Tipo like:

class Tipo implements \JsonSerializable
{
    // ...

    public function jsonSerialize() {
        return [
            'some key' => $this->someValue, // ...
        ];
    }
}

this, paired with the ArrayCollection::toArray should be enough.


Other than that you can use some sort of serializer, eg:

Why don't you use Symfony\\Component\\HttpFoundation\\JsonResponse ?

You could do something like this:

use Symfony\Component\HttpFoundation\JsonResponse;

$response = new JsonResponse();
$response->setData(array(
    'data' => $u->getIdtipo()
));

Then you can return the response:

return $response;

If not, then you can make use of the JMSSerializerBundle . Once installed you can do something like:

$serializer = $container->get('jms_serializer');
$serializer->serialize($data, $format);
$data = $serializer->deserialize($inputStr, $typeName, $format);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM