为了账号安全,请及时绑定邮箱和手机立即绑定

symfony fosrestbundle 实例化entity为json时把所有relations都获取了,怎么更改?

symfony fosrestbundle 实例化entity为json时把所有relations都获取了,怎么更改?

PHP
暮色呼如 2019-03-18 18:11:11
背景 三个实体关系如下 Reply BelongsTo Topic Reply BelongsTo User User ManyToMany Followers(Users)自关联 控制器方法 /** *@Route("/topics/{id}/replies", name="topic_add_reply") *@Method('POST') */ public function addTopicReply($id, Request $request) { $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); $topic = $this->getTopicManager()->findTopicById($id); $reply = $this->getReplyManager()->createReply($topic, $this->getUser()); $form = $this->createForm(TopicReplyType::class, $reply, [ 'csrf_protection' => false ]); $form->handleRequest($request); $view = $this->view()->setFormat('json'); if ($form->isSubmitted() && $form->isValid()) { $this->getReplyManager()->saveReply($reply); $view->setData(['reply' => $reply]); } else { $view->setStatusCode(400) ->setData(array( 'form' => $form, )); } return $this->handleView($view); } 结果 json的结果把相关的relation都取出来了,七大姑八大姨一大坨用不到的数据 问题 无疑这个效率是非常低的,怎么才可以灵活的控制要获取的relation呢? 比如在这个方法中,我只想获取reply实体本身;可能在另外一个方法中我希望实例化reply和它所属的topic;又可能在第三个方法中我可以实例化reply,它的topic和它的user; 类似在cakephp中的解决方案 $reply = $Replies->findById(1)->contain(['Topic', 'User.Followers']) 通过contain方法可以灵活的控制你想获取到的relations
查看完整描述

1 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

自问自答吧,在jms serializer和官方的serializer里支持通过anotation 对关联分组

查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 411 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信