我的实体中有一个属性链接到另一个实体:
/**
* @Groups({"bookReviews"})
* @ORM\ManyToOne(targetEntity="Book\MainBundle\Entity\Book", inversedBy="reviews")
* @ORM\JoinColumn(name="bookID", referencedColumnName="id")
*/
private $bookID;
在我的控制器中调用它时:
public function getReviewsAction()
{
$serializer = $this->get('serializer');
$em = $this->getDoctrine()->getManager();
$reviews = $em->getRepository('BookMainBundle:Review')->findAll();
$data = $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default')));
return $this->handleView($this->view($reviews));
}
这将检索具有以下结果的JSON:
{
"id": 17,
"book_i_d": {
"id": 10,
"author": "J.K Rowling",
"title": "Harry Potter: Philosopher's Stone",
"posted": "2017-01-03T04:19:18+0000",
"summary": "Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel, first published in 1997 by Bloomsbury. It was published in the United States as Harry Potter and the Sorcerer's Stone by Scholastic Corporation in 1998. The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry. With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.",
"image": "cde5910f46d0e6bed33ffa18aa24ec5c.jpeg"
},
"posted": "2017-01-03T04:19:19+0000",
"review": "The author started Harry's journey with this book. It's the beginning and it's bloody brilliant!"
}
然而,正如您所注意到的那样......检索了本书的无关信息。此时,我想要检索的唯一细节是书的ID。
我该怎么办?
答案 0 :(得分:0)
在Review类
中创建特定方法public function findAllAndOnlyBookId()
{
$query = $this->createQueryBuilder('u')
->select('a.id, b.id')
->from('BookMainBundle\Review', 'a')
->leftJoin('a.book_id', 'b');
;
return $query->getQuery()->getResult();
}
打电话给你的方法后
$reviews = $this->getDoctrine()->getRepository('BookMainBundle:Review')-> findAllAndOnlyBookId();
P.S。我不知道查询或路径是否正确,因为我需要尝试它,但我认为概念很清楚
答案 1 :(得分:0)
我在这里看到两种解决方案。
为序列化程序创建一个虚拟属性,并将其分配给实体中仅返回id的自定义方法,从序列化程序上下文中删除$ bookID。
@Serializer \ VirtualProperty()
@Serializer \ SerializedName(" book_id&#34)
@Serializer \组({" bookReviewes"})
另一个选项是在链接实体中正确分配序列化程序注释。所有字段的用户不同的上下文。
请确保您使用正确的上下文序列化实体。因为现在你正在使用"默认"组,但在注释中,它设置为" bookReviews"。