好吧,回頭再來,我會盡量簡化我的問題。Symfony教條ManyToMany單向映射
首先,我有2個實體
Post
PostRating
我已經創造了他們之間的單向多對多的關係,因爲我只需要評級被添加到每個崗位,如果我嘗試後映射到PostRating太,我收到循環引用錯誤。
郵政實體,它創建了3臺post_has_rating,PostRating實體內部沒有映射,它workes像預期,評級收集被添加到每個崗位,但如果我想找到一個等級,並進行必要的修改,然後它會比預期的更令人頭痛。
/**
* Post have many PostRating
* @ORM\ManyToMany(targetEntity="PostRating")
* @ORM\JoinTable(name="post_has_rating",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="postrating_id", referencedColumnName="id", unique=true)}
* )
*/
protected $ratings;
PostController中thumbAction,簡單的一句話 「ratingAction」
/**
* Search related videos from youtube
* @Route("/post/thumb", name="post_thumb")
* @param Request $request
* @return string
*/
public function thumbAction (Request $request) {
$content = json_decode($request->getContent());
$serializer = $this->get('serializer');
$em = $this->getDoctrine()->getManager();
$postRatingRepo = $this->getDoctrine()->getRepository(PostRating::class);
$postRepo = $this->getDoctrine()->getRepository(Post::class);
$me = $this->getUser()->getId();
/** @var PostRating $rating */
$rating = $postRatingRepo->findOneBy(['userId' => $me]);
/** @var Post $post */
$post = $postRepo->find($content->id);
if ($post->getRatings()->contains($rating)) {
$post->removeRating($rating);
$em->remove($rating);
}
$rating = new PostRating();
$rating->setUserId($me);
switch ($content->action) {
//NVM about those hardcoded words, they are about to be removed
case 'up':
$rating->setRating(1);
break;
case 'down':
$rating->setRating(0);
break;
}
$post->addRating($rating);
$em->persist($rating);
$em->persist($post);
$em->flush();
return new JsonResponse($serializer->normalize(['success' => 'Post thumbs up created']));
}
問題:
$rating = $postRatingRepo->findOneBy(['userId' => $me]);
該行需要有帖子ID也爲$post->getRatings()->contains($rating)
,現在即時得到所有raitings ,我曾創建過,但它會拋出錯誤,如果我添加它,未知列
我應該創建自定義存儲庫,所以我可以使用DQL創建類似「findRating」的東西?
OR
我可以讓郵政和PostRating實體相互映射更簡單的方法,我真的不希望多到一對多的關係,因爲我沒有看到使用它
我想,一個一對多的關係應該是足夠的,因爲一個評級是隻能從一個職位。除此之外,您可以使用DQL或查詢構建器在存儲庫中編寫自己的查詢。 –
謝謝,生病只是使用一對多,如果我記得沒錯,我已經嘗試過了,並且得到了循環引用錯誤。 –
@FrankB這實際上是你聲明OneToMany單向關係的方式。註釋OneToMany僅用於雙向關係。 – OlivierC