0

我将 Symfony2 与 Doctrine 和 FOS Rest Bundle(使用 JMS 序列化程序)一起使用。有两个实体 FatherChild

<?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"
    }
]

实现这一目标的最佳方法是什么?

4

2 回答 2

1

您可以尝试使用 Hateoas 捆绑包之一,例如:BazingaHateoasBundleFSCHateoasBundle。您可以使用http://knpbundles.com进行更多搜索

于 2013-11-27T19:11:23.220 回答
0

您可以使用virtualProperty使用自定义逻辑的“父亲”来返回“父亲”字段的值。

请参阅: JMSSerializer YAML 配置参考

于 2014-03-09T02:19:53.940 回答