【发布时间】:2019-04-11 09:25:47
【问题描述】:
Symfony 4. 我有两个实体,Cat 和 Owner。
class Cat
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @Groups("cats")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("cats")
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Owner", mappedBy="cat")
* @Groups("cats")
*/
private $owners;
}
class Owner
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @Groups("cats")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("owners")
*/
private $name;
}
我的 API 端点需要返回 2 个密钥,owners(所有所有者的列表)和 cats(所有猫及其所有者的列表)。
public function index()
{
$repository = $this->getDoctrine()->getRepository(Owner::class);
$owners = $repository->findAll();
$repository = $this->getDoctrine()->getRepository(Cat::class);
$cats = $repository->findAll();
return $this->json([
'owners' => $owners,
'cats' => $cats,
], 200, [], ['groups' => ['owners', 'cats']]);
}
这可行,但有 1 个问题:cats 列表包含每个所有者的完整所有者信息,即:
{
"owners": [
{
"id": 1,
"name": "John Smith"
}
],
"cats": [
{
"id": 1,
"name": "Miaow",
"owners": [
{
"id": 1,
"name": "John Smith"
}
]
}
]
}
我想要的是cat 对象中的owners 键只返回所有者的id,如下所示:
{
"owners": [
{
"id": 1,
"name": "John Smith"
}
],
"cats": [
{
"id": 1,
"name": "Miaow",
"owners": [
1
]
}
]
}
【问题讨论】:
标签: php symfony serialization