我正在使用带有Doctrine和FOS Rest Bundle(使用JMS序列化程序(的Symfony2。有两个实体父和子
:<?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"
}
]
实现这一目标的最佳方法是什么?
您可以尝试使用Hateoas捆绑包之一,例如:BazingaHateoasBundle或FSCHateoasBundle。您可能可以使用 http://knpbundles.com 搜索更多内容
您可以使用
"父亲"virtualProperty
,该使用自定义逻辑返回"父亲"字段的值。
看:JMSSerializer YAML 配置参考