背景
三個(gè)實(shí)體關(guān)系如下
Reply BelongsTo Topic
Reply BelongsTo User
User ManyToMany Followers(Users)自關(guān)聯(lián)
控制器方法
/**
*@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);
}
結(jié)果
json的結(jié)果把相關(guān)的relation都取出來了,七大姑八大姨一大坨用不到的數(shù)據(jù)
問題
無疑這個(gè)效率是非常低的,怎么才可以靈活的控制要獲取的relation呢?
比如在這個(gè)方法中,我只想獲取reply實(shí)體本身;可能在另外一個(gè)方法中我希望實(shí)例化reply和它所屬的topic;又可能在第三個(gè)方法中我可以實(shí)例化reply,它的topic和它的user;
類似在cakephp中的解決方案
$reply = $Replies->findById(1)->contain(['Topic', 'User.Followers'])
通過contain方法可以靈活的控制你想獲取到的relations
1 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
自問自答吧,在jms serializer和官方的serializer里支持通過anotation 對(duì)關(guān)聯(lián)分組
- 1 回答
- 0 關(guān)注
- 420 瀏覽
添加回答
舉報(bào)
0/150
提交
取消