简体   繁体   English

Symfony:如何获取与 oneToMany 关系相关的所有用户帖子

[英]Symfony : how to get all user posts related with oneToMany relation

I have two entity User and Booking which are related with oneToMany relationship, when a user ake a booking the user id is saved in the user_id column table of booking, I want in my controller to retrieve all the user's booking !我有两个实体 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
        ]);
    }

when trying to get the connected user and call getBookings() method it doesn't return any thing !当尝试获取连接的用户并调用 getBookings() 方法时,它不返回任何东西!

here what does $this->getUser return :这里 $this->getUser 返回什么:

在此处输入图片说明

You can print it from twig by using您可以使用 twig 打印它

{% for booking in user.bookings %}
    {{booking}}
{% endfor %}

Or retrieve it into your controller with PHP:或者使用 PHP 将其检索到您的控制器中:

foreach($user->getBookings() as $booking){
    echo $booking->getYourField();
}

我找到了解决方案,我只是忘记将 fetch EAGER 添加到 User 和 Booking 之间的 OneToMany 关系中!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM