我想创建一个这样的模型。
{
"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);
}
ITMISS