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

背景

三个实体关系如下

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都取出来了,七大姑八大姨一大坨用不到的数据
clipboard.png

问题

无疑这个效率是非常低的,怎么才可以灵活的控制要获取的relation呢?

比如在这个方法中,我只想获取reply实体本身;可能在另外一个方法中我希望实例化reply和它所属的topic;
又可能在第三个方法中我可以实例化reply,它的topic和它的user;

类似在cakephp中的解决方案

$reply = $Replies->findById(1)->contain(['Topic', 'User.Followers'])   

通过contain方法可以灵活的控制你想获取到的relations

阅读 3k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题