StrikeForceZero
StrikeForceZero

Reputation: 2379

How to get an array of ids from a Doctrine Collection during serialization

I am trying to json encode a doctrine object and instead of serializing each item in its collection property;

I want to return an array of ids like:

{"children":[200,201],"id":1}

instead of:

{"children":[{"parents":[],"id":200},{"parents":[],"id":201}],"id":1}

I'm using the jmsserializerbundle to serialize the doctrine object I've tried to create a virtual property and loop through each item in the collection property, which works but feels dirty...

Controller:

$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($parent, 'json');

Entity:

/**
 * Parent
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Parent
{
    [...]

    /**
     * @ORM\ManyToMany(targetEntity="Children",  inversedBy="parents")
     * @Exclude
     */
    private $children;

    /**
     * @VirtualProperty
     * @SerializedName("children")
     */
    public function getChildrenId()
    {
        $children= array();
        foreach ($this->children $child){
            $children[] =  $child->getId();
        }
        return $children;
    }

    [...]

Upvotes: 0

Views: 4769

Answers (1)

dchesterton
dchesterton

Reputation: 2110

You can use the @Accessor annotation to specify a method to be used when serializing a property, which is a cleaner way of doing it.

/**
 * Parent
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Parent
{
    [...]

    /**
     * @ORM\ManyToMany(targetEntity="Children",  inversedBy="parents")
     * @Accessor(getter="getChildrenId")
     */
    private $children;

    public function getChildrenId()
    {
        $children = array();
        foreach ($this->children as $child){
            $children[] = $child->getId();
        }
        return $children;
    }

    [...]

You could then also easily implement a setter if you needed to deserialize the data.

    /**
     * @ORM\ManyToMany(targetEntity="Children",  inversedBy="parents")
     * @Accessor(getter="getChildrenId", setter="setChildrenId")
     */
    private $children;

    public function setChildrenId($ids)
    {
        ...
    }

Upvotes: 2

Related Questions