【问题标题】:How to get an array of ids from a Doctrine Collection during serialization如何在序列化期间从 Doctrine 集合中获取 id 数组
【发布时间】:2015-02-10 11:37:25
【问题描述】:

我正在尝试对一个学说对象进行 json 编码,而不是序列化其集合属性中的每个项目;

我想返回一个 id 数组,例如:

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

代替:

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

我正在使用jmsserializerbundle 序列化学说对象 我试图创建一个虚拟属性并循环遍历集合属性中的每个项目,这可以工作但感觉很脏......

控制器:

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

实体:

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

    [...]

【问题讨论】:

    标签: php symfony serialization doctrine-orm jmsserializerbundle


    【解决方案1】:

    您可以使用@Accessor annotation 指定序列化属性时要使用的方法,这是一种更简洁的方式。

    /**
     * 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;
        }
    
        [...]
    

    如果您需要反序列化数据,您还可以轻松实现 setter。

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

    【讨论】:

    • 啊,好的。这似乎更清洁。您知道在控制器中执行此操作的方法吗? jmsserializerbundle 的预序列化处理程序看起来很有希望......
    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2017-10-16
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多