我将 Symfony2 与 Doctrine 和 FOS Rest Bundle(使用 JMS 序列化程序)一起使用。有两个实体 Father和Child:
<?php
namespace Acme\Bundle\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Father
*
* @ORM\Table()
* @ORM\Entity
*/
class Father {
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
**/
private $id;
/**
* @ORM\Column(name="name", type="string", length=255)
*/
protected $name;
}
和
namespace Acme\Bundle\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Child
*
* @ORM\Table()
* @ORM\Entity
*/
class Child {
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
**/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Acme\Bundle\CoreBundle\Entity\Father")
**/
private $father;
}
有路线:
acme_test_child_all:
defaults: { _controller: AcmeCoreBundle:Test:childAll }
path: /child/
acme_test_father_get:
defaults: { _controller: AcmeCoreBundle:Test:fatherGet }
path: /father/{id}
最后有一个控制器对这些路由执行操作:
<?php
namespace Acme\Bundle\CoreBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class TestController extends Controller {
/**
* @Rest\View()
*/
public function childAllAction() {
$children = $this->getDoctrine()
->getRepository('AcmeCoreBundle:Child')
->findAll();
return $children;
}
/**
* @Rest\View()
*/
public function fatherGetAction($id) {
$father = $this->getDoctrine()
->getRepository('AcmeCoreBundle:Child')
->findById($id);
return $father;
}
}
当我调用GET /child/时,我得到了预期的响应:
[
{
"id": 1,
"father": {
"id":1,
"name":"Father"
}
}
]
我想获得父亲资源的uri,而不是嵌套响应,即:
[
{
"id": 1,
"father": "/father/1"
}
]
实现这一目标的最佳方法是什么?