我有两个实体User和Booking,它们与oneToMany关系相关,当用户进行预订时,用户ID保存在预订的user_id列表中,我希望在控制器中检索所有用户的预订! >
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="bookings")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* @ORM\OneToMany(targetEntity=Booking::class, mappedBy="user")
*/
private $bookings;
/**
* @return Collection|Booking[]
*/
public function getBookings(): Collection
{
return $this->bookings;
}
public function addBooking(Booking $booking): self
{
if (!$this->bookings->contains($booking)) {
$this->bookings[] = $booking;
$booking->setUser($this);
}
return $this;
}
/**
* @Route("/user/profile/my-bookings", name="user.profile.bookings")
*/
public function getUserBookings(){
$user = $this->getUser()->getBookings();
return $this->render('user/user.bookings.html.twig', [
'user'=>$user
]);
}
当尝试获取连接的用户并调用getBookings()方法时,它不会返回任何东西!
$ this-> getUser返回什么:
答案 0 :(得分:1)
您可以使用
从树枝上打印它{% for booking in user.bookings %}
{{booking}}
{% endfor %}
或使用PHP将其检索到您的控制器中
foreach($user->getBookings() as $booking){
echo $booking->getYourField();
}
答案 1 :(得分:0)
我找到了解决方案,我只是忘了在用户和预订之间的OneToMany关系中添加获取EAGER了!