猿问

api-platform odm iri 引用不会被转换为 json 中的对象

我想创建一个这样的模型。


{

  "id": 7653,

  "name": "Vortl 123",

   "category": [

    {

      "name": "Electronic",

      "url": "electronic",

      "id": 1

    }, {

      "name": "Phone",

      "url": "phone",

      "id": 2

    },

    {

      "name": "Mobile Phone",

      "url": "mobile-phone",

      "id": 3

    }

}

我使用原则 odm 引用创建了文档。代码就是这些。


这是产品类。


/**

 * @ApiResource

 *

 * @Document

 */

class Product

{


    /**

     * @ODM\Id(strategy="INCREMENT", type="integer")

     */

    private $id;


    /**

     * @ODM\Field(type="string")

     * @Assert\NotBlank

     */

    public $name;


    public function __construct()

    {

        $this->categories = new ArrayCollection();

    }


    /**

     * @ODM\ReferenceMany(targetDocument=Category::class, inversedBy="product", cascade={"persist"}, storeAs="id")

     */

    public $categories;


    /**

     * @return mixed

     */

    public function getId(): ?int

    {

        return $this->id;

    }



    /**

     * @param Category $category

     */

    public function addCategory(Category $category): void

    {

        $this->categories->add($category);

    }


    public function removeCategory(Category $category): void

    {


        $category->product = null;

        $this->categories->removeElement($category);

    }


月关宝盒
浏览 110回答 1
1回答

ITMISS

您必须至少添加一组normalizationContext:<?php/**&nbsp;* @ApiResource(&nbsp;*&nbsp; &nbsp; &nbsp;normalizationContext={"groups" = {"product:read"}}&nbsp;* )&nbsp;*&nbsp;* @Document&nbsp;*/class Product{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @ODM\Id(strategy="INCREMENT", type="integer")&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private $id;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @ODM\Field(type="string")&nbsp; &nbsp; &nbsp;* @Assert\NotBlank&nbsp; &nbsp; &nbsp;* @Groups({"product:read"})&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public $name;&nbsp; &nbsp; // ...}和Category:<?php/**&nbsp;* @ApiResource&nbsp;*&nbsp;* @Document&nbsp;*/class Category{&nbsp; &nbsp; // ...&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @ODM\Field(type="string")&nbsp; &nbsp; &nbsp;* @Assert\NotBlank&nbsp; &nbsp; &nbsp;* @Groups({"product:read"})&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public $name;&nbsp; &nbsp; // ...}之后,您应该会看到Category具有属性的对象$name
随时随地看视频慕课网APP
我要回答