【问题标题】:Deserialize JSON with nested categories使用嵌套类别反序列化 JSON
【发布时间】:2018-08-01 04:16:28
【问题描述】:

我的控制器类:

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 类的对象。但是怎么让他也报名呢? 我怎样才能做到这一点?可能我有什么不明白的……

【问题讨论】:

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


    【解决方案1】:

    您需要有一个用于序列化程序的.yml 配置文件。在你的情况下 - Entity.Category.yml。 在这个文件中添加嵌套实体的属性,将他设置为你的实体类型,并确保访问器(setter、getter)。

    【讨论】:

    • 我该怎么做? add property of nested entities?
    • 你有输出属性parentId吗?即使只有标量值。
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多