假设我有这个网址:
/people/1/friends
人和朋友都是对象,一个人可以有很多朋友
FriendController看起来像这样
class FriendController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EpiForumBundle:Friend')->findAll();
return $this->render('EpiForumBundle:Friend:index.html.twig', array(
'entities' => $entities,
));
}
}
此索引操作效果很好但是您可以看到它返回数据库中的每个朋友。我想和“people_id' == 1.我如何选择想要的朋友?换句话说,我怎样才能获得告诉我们特定人的参数?
更新
路线
friend:
pattern: /
defaults: { _controller: "EpiForumBundle:Friend:index" }
答案 0 :(得分:1)
您可以尝试使用ParamConverters:
/**
* @Route("/people/{id}/friends")
* @ParamConverter("person", class="EpiForumBundle:Person")
* @Template
*/
public function indexAction(Person $person)
{
return array(
'friends' => $person->getFriends()
);
}
答案 1 :(得分:0)
您的路线应如下:
friend:
pattern: /people/{id}/friends
defaults: { _controller: "EpiForumBundle:Person:friends" }
然后你应该有一个控制器方法,如:
class PersonController
{
public function friendsAction($id)
{
$friends = $this->getRepository('EpiForumBundle:Friend')->findBy(array(
'person' => $id
));
return $this->render('EpiForumBundle:Person:friends.html.twig', array(
'friends' => $friends,
));
}
}
请注意,我的路线与您的路线略有不同。我已经在friendsAction
内拨打了PersonController
的路线。我还使用了一个更具描述性的名称来描述我传递给模板的实体。
如果你想提升一个档次,请使用ParamConverter注释,你可以输入提示Person对象,ID将在幕后转换。您可能希望将Person传递给模板。
class PersonController
{
/**
* @ParamConverter("person", class="EpiForumBundle:Person")
*/
public function friendsAction(Person $person)
{
$friends = $this->getRepository('EpiForumBundle:Friend')->findBy(array(
'person' => $person
));
return $this->render('EpiForumBundle:Person:friends.html.twig', array(
'person' => $person,
'friends' => $friends,
));
}
}
此外,正如其他答案所示,使用您的路线注释比使用Yaml更直观。所以一旦你理解了这一切是如何运作的,请继续阅读:http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html