1

In my app I have 2 entities; User & Booking.

Booking entity:

namespace App\Entity;

/**
 * @ORM\Table(name="booking")
 * @ORM\Entity(repositoryClass="App\Repository\BookingRepository")
 */
class Booking
{
/**
 * @ORM\Column(type="boolean")
 * @Assert\NotBlank()
 */
private $isActive;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="bookings")
 */
private $user;

User entity:

/**
 * @ORM\Table(name="app_user")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(fields="email", message="This email address is already in use")
 */
class User implements AdvancedUserInterface
{

/**
 * @ORM\Column(type="string", length=255, unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Booking", mappedBy="user")
 * @Expose
 */
private $bookings;

/**
 * User constructor.
 */
public function __construct()
{
    $this->bookings = new ArrayCollection();
}

I tried to add a function to my user entity that returns the active booking, I tried this:

/**
 * @return mixed
 */
public function getActiveBooking()
{
    foreach( $this->bookings as $booking ) {
        if( $booking->getIsActive() ) {
            return $booking;
        }
    }
}

But I get the following error: Error: Call to a member function getRoom() on null

When I call it using $user->getActiveBooking()->getRoom()->getId()

2 Answers 2

1

Make sure that the user you are working with has an active booking.

getActiveBooking() is returning null because it seems user does not have an active booking.

That's why you are getting an error that you cannot call getRoom() on null because the previous function has returned null.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I have checked the database, and is_active field is set to 1
And the user_id is the same id as the user you are using? Have you tried dump ing the user and checking the associations?
0

Have you tried to add a joinColumn like this:

 /**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="bookings")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
 */
private $user;

2 Comments

Thank you for your reply, but the $user relationship is already present in the booking entity
Well. Have you tried to see if your if is true? foreach( $this->bookings as $booking ) { if( $booking->getIsActive() ) { die("its true once at least"); } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.