使用嵌套类别反序列化JSON

时间:2018-02-21 14:27:02

标签: mysql doctrine-orm relationship jmsserializerbundle symfony-3.4

我的控制器类:

public function postAction(Request $request)
{
    $content = $request->getContent();

    $category = $this->get('jms_serializer')->deserialize($content,'AppBundle\Entity\Category','json');

    $errors = $this->get('validator')->validate($category);

    if (count($errors) > 0) {
        return new View("NAME LENGTH MUST BE >4",Response::HTTP_BAD_REQUEST);
    } else {
        $em = $this->getDoctrine()->getManager();
        $em->persist($category);
        $em->flush();

        return new View($category, Response::HTTP_OK);
    }
}

实体:

class Category
{

    private $id;
    private $parent;
    public function getChildren()
    {
        return $this->children;
    }
    private $children;

    public function __construct()
    {
        $this->children = new ArrayCollection();
    }

   //setters and getters

Doctrine.yml:

AppBundle\Entity\Category:
  type: entity
  oneToMany:
        children:
            targetEntity: AppBundle\Entity\Category
            mappedBy: parent
            orderBy:
                name: ASC
  manyToOne:
        parent:
            targetEntity: AppBundle\Entity\Category
            inversedBy: children
            joinColumn:
                name: parentId
                referencedColumn: id
  table: category
  repositoryClass: AppBundle\Repository\CategoryRepository
  id:
      id:
          column: id
          type: integer
          id: true
          generator:
              strategy: AUTO
  fields:
      name:
          type: string
          lenght: 255

当我像这样发送POST json请求时:

{
    "name": "Child to 8",
    "parentId": "8"
}

在MySQL表中我没有收到parentId:

mysql> select * from category;
+----+--------------------+----------+
| id | name               | parentId |
+----+--------------------+----------+
|  1 | Primary Category   |     NULL |
|  2 | Secondary Category |        1 |
|  3 | D_child            |        1 |
|  4 | F_child            |        1 |
|  5 | Z_child            |        1 |
|  6 | Y_child            |        1 |
|  7 | H_child            |        1 |
|  8 | A_child            |        1 |
|  9 | Child to 8         |     NULL |<----- must be 8
+----+--------------------+----------+

但是在反序列化后我得到了这个:

{
    "id": 9,
    "name": "Child to 8"
}

我知道id是一个整数,但parentId已经是类Category的对象。但如何让他也签约呢? 我怎样才能做到这一点?也许我不明白......

1 个答案:

答案 0 :(得分:1)

您需要为序列化程序提供.yml配置文件。在你的情况下 - Entity.Category.yml。 在此文件中添加嵌套实体的属性,将其设置为您实体的类型,并确保访问者(setter,getter)。