我想创建一个这样的模型。{ "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); }
1 回答
ITMISS
TA贡献1871条经验 获得超8个赞
您必须至少添加一组normalizationContext:
<?php
/**
* @ApiResource(
* normalizationContext={"groups" = {"product:read"}}
* )
*
* @Document
*/
class Product
{
/**
* @ODM\Id(strategy="INCREMENT", type="integer")
*/
private $id;
/**
* @ODM\Field(type="string")
* @Assert\NotBlank
* @Groups({"product:read"})
*/
public $name;
// ...
}
和Category:
<?php
/**
* @ApiResource
*
* @Document
*/
class Category
{
// ...
/**
* @ODM\Field(type="string")
* @Assert\NotBlank
* @Groups({"product:read"})
*/
public $name;
// ...
}
之后,您应该会看到Category具有属性的对象$name
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消