I am currently working in a project using Symfony3.4, a project is about booking rooms of an hotel.
I have two entities room(id,...)
and bookings(room,check_in,check_out,...)
and the relation between them is OneToMany
.
I am trying to retrieve rooms that are not booked by check_in
and check_out
fields.
I did a function in RoomRepository
called findRoomsNotBookedByCheckInCheckOut
public function findRoomsNotBookedByCheckInCheckOut(Request $request) {
$em = $this->getEntityManager();
$q = $em->createQuery("SELECT r FROM AppBundle:Room r "
. "WHERE r NOT IN ( "
. "SELECT b.room FROM AppBundle:Bookings b "
. "WHERE NOT ( "
. "b.checkOut <= :checkIn "
. "OR b.checkIn >= :checkOut "
. ") "
. ") ORDER BY r.id")
->setParameter('checkIn', "'".$request->query->get('check-out')."'")
->setParameter('checkOut', "'".$request->query->get('check-in')."'");
die($q->getSQL());
return $q->getResult();
}
When I call this function from the controller
private function roomsByCheckInCheckOut(Request $request, $em) {
if ($request->query->get('check-in') != null && $request->query->get('check-out') != null) {
$rooms = $em->getRepository('AppBundle:Room')->findRoomsNotBookedByCheckInCheckOut($request);
}
return null;
}
I get an error which is :
[Semantical Error] line 0, col 57 near 'room FROM AppBundle:Bookings': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
I tried to fixed by change the b.room
to b.room.id
:
public function findRoomsNotBookedByCheckInCheckOut(Request $request) {
$em = $this->getEntityManager();
$q = $em->createQuery("SELECT r FROM AppBundle:Room r "
. "WHERE r NOT IN ( "
. "SELECT b.room.id FROM AppBundle:Bookings b "
. "WHERE NOT ( "
. "b.checkOut <= :checkIn "
. "OR b.checkIn >= :checkOut "
. ") "
. ") ORDER BY r.id")
->setParameter('checkIn', "'".$request->query->get('check-out')."'")
->setParameter('checkOut', "'".$request->query->get('check-in')."'");
die($q->getSQL());
return $q->getResult();
}
and I get another error which is :
[Semantical Error] line 0, col 62 near 'id FROM AppBundle:Bookings': Error: Class AppBundle\Entity\Bookings has no field or association named room.id
which is logic because the entity bookings
does not have a room.id
but it has room
.
I tried again to solve by changing b.room
to b
and the function become :
public function findRoomsNotBookedByCheckInCheckOut(Request $request) {
$em = $this->getEntityManager();
$q = $em->createQuery("SELECT r FROM AppBundle:Room r "
. "WHERE r NOT IN ( "
. "SELECT b FROM AppBundle:Bookings b "
. "WHERE NOT ( "
. "b.checkOut <= :checkIn "
. "OR b.checkIn >= :checkOut "
. ") "
. ") ORDER BY r.id")
->setParameter('checkIn', "'".$request->query->get('check-out')."'")
->setParameter('checkOut', "'".$request->query->get('check-in')."'");
die($q->getSQL());
return $q->getResult();
}
it worked fine without any error but it didn't retrieve the right result.
note: I tested the sql query in MySQL database and I get the right result