简体   繁体   中英

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;
    }

    [...]

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)
    {
        ...
    }

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