Symfony : How to fetch all object data from entity related with oneToMany relationship

Tags: , , ,



I have “Car” and “Booking” entities related with oneToMany relationship :

<?php

namespace AppEntity;
    
/**
 * @ORMEntity(repositoryClass=CarRepository::class)
 * @UniqueEntity("registrationNumber")
 * @VichUploadable
 */

class Car
{

    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     * @AssertLength(min=3, max=9)
     */
    private $registrationNumber;

    /**
     * @ORMOneToMany(targetEntity=Booking::class, mappedBy="car")
     */
    private $bookings;

/**
     * @return Collection|Booking[]
     */
    public function getBookings(): Collection
    {
        return $this->bookings;
    }

}

<?php

namespace AppEntity;

/**
 * @ORMEntity(repositoryClass=BookingRepository::class)
 */
class Booking
{
    const STATUS = [
        0 => 'Pending',
        1 => 'Canceled',
        2 => 'Confirmed',
        3 => 'Approved',
    ];


    public function  __construct()
    {
        $this->request_date = new DateTime('now');
    }


    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    
    /**
     * @ORMManyToOne(targetEntity=Car::class, inversedBy="bookings")
     * @ORMJoinColumn(nullable=false)
     */
    private $car;

    /**
     * @ORMColumn(type="string", length=255, options={"default": "Pending"})
     */
    private $status = self::STATUS[0];

    
    public function getCar(): ?Car
    {
        return $this->car;
    }

    public function setCar(?Car $car): self
    {
        $this->car = $car;

        return $this;
    }

    public function getStatus(): ?string
    {
        return $this->status;
    }

    public function getBookingStatus(): ?string
    {
        return self::STATUS[$this->status];
    }

    public function setStatus(string $status): self
    {
        $this->status = $status;

        return $this;
    }
 
}

public function book(Request $request, Car $car)
    {
        $booked_car = $car;
        $booking = new Booking();
        $booking->setCar($booked_car);
        $form = $this->createForm(BookingType::class, $booking);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $booking = $form->getData();
            $this->em->persist($booking);
            $this->em->flush();
            $this->addFlash('success', 'Démande envoyée avec success');

            return $this->redirectToRoute('car.index');
        }
        $this->addFlash('error', 'une erreur dans le système');
        return $this->render('booking/book.html.twig',[
            'booking' => $booking,
            'form' => $form->createView()
        ]);
    }

When dump $booking variable in the twig or in the index page which list all bookings, every car object in booking object has only the id field, others are null ! I want to get every field of car object related to booking full of data to show it in the twig view ! in the method book I get the id variable sent with request and put it with setCar method, should I create a query to search byId and affect every attribute one by one !!

dump image

Answer

That kind of relation is in lazy loading by default. So since you didn’t call any getter of the car object, you only have the id displayed (since it’s stored in the booking object too). But this is only in the context of the dump, as soon as you’ll try to use a getter of the car (except getId) it will load the rest.

If you really need the whole car data to be loaded with the booking data, you can use fetch="EAGER" in the ManyToOne relation, but you would need a valid reason to do that.



Source: stackoverflow