具有嵌套类别的JSON的绝对序列化



我的控制器类:

public function postAction(Request $request)
{
    $content = $request->getContent();
    $category = $this->get('jms_serializer')->deserialize($content,'AppBundleEntityCategory','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:

AppBundleEntityCategory:
  type: entity
  oneToMany:
        children:
            targetEntity: AppBundleEntityCategory
            mappedBy: parent
            orderBy:
                name: ASC
  manyToOne:
        parent:
            targetEntity: AppBundleEntityCategory
            inversedBy: children
            joinColumn:
                name: parentId
                referencedColumn: id
  table: category
  repositoryClass: AppBundleRepositoryCategoryRepository
  id:
      id:
          column: id
          type: integer
          id: true
          generator:
              strategy: AUTO
  fields:
      name:
          type: string
          lenght: 255

当我发送这样的邮政请求时:

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

在MySQL表中,我不收到parenterid:

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已经是类别类别的对象。但是如何做到这一点,以便他也签约?我怎样才能做到这一点?也许我不明白什么...

您需要有一个用于序列化器的.yml配置文件。在您的情况下-Entity.Category.yml。在此文件中,添加嵌套实体的属性,将其设置为您的实体类型,并确定登录器(setter,getter(。

相关内容

  • 没有找到相关文章