Skip to content
Advertisement

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 !

/**
 * @ORMManyToOne(targetEntity=User::class, inversedBy="bookings")
 * @JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

    public function setUser(?User $user): self
    {
        $this->user = $user;

        return $this;
    }

/**
     * @ORMOneToMany(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 !

here what does $this->getUser return :

enter image description here

Advertisement

Answer

I found the solution, I just forgot to add fetch EAGER to the OneToMany relationship between User and Booking !

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement