在实现中,您可以使用API资源类进行自定义。
首先,将API资源类(如Order)的一对多关系(如OrderItem)设置为返回单个对象而不是数组。这可以通过设置@ApiSubresource属性来实现。然后,使用@Groups注释将子资源的组名称设置为可嵌套的。最后,创建一个新的API资源类(如OrderCollection)来嵌套子资源。
以下是代码示例:
// Order.php
use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\Common\Collections\Collection;
/**
@ApiResource / class Order { /*
public function getItems(): Collection { return $this->items; } }
// OrderItem.php
use ApiPlatform\Core\Annotation\ApiResource;
/**
// OrderCollection.php
use ApiPlatform\Core\Annotation\ApiResource;
/**
@ApiResource(
collectionOperations={
"get",
"post"
},
itemOperations={
"get"
}
) / class OrderCollection { /*
public function __construct(Order $order) { $this->order = $order; }
public function getItems() { return $this->order->getItems(); } }
使用这种方法,您可以确保APIPlatform在一对多关系上返回对象的对象而不是数组。