我正在编写一些简单的脚本,但无法解决这个问题。所以就在这里。
/**
* Booking
* @ORM\Table()
* @ORM\Entity(repositoryClass="Tons\BookingBundle\Entity\BookingRepository")
* @UniqueEntity(fields={"room", "since", "till"}, repositoryMethod="getInterferingRoomBookings")
* @Assert\Callback(methods={"isSinceLessThanTill"}, groups={"search","default"})
*/
class Booking
和存储库方法
/**
* Get room state for a certain time period
*
* @param array $criteria
* @return array
*/
public function getInterferingRoomBookings(array $criteria)
{
/** @var $room Room */
$room = $criteria['room'];
$builder = $this->getQueryForRoomsBooked($criteria);
$builder->andWhere("ira.room = :room")->setParameter("room", $room);
return $builder->getQuery()->getArrayResult();
}
问题是这适用于它应该的创建方法,但是在更新现有实体时 - 它违反了这个约束。
我尝试添加 Id 约束,但是在创建实体时,id 为空,因此存储库方法甚至没有启动。我也尝试删除实体然后重新创建它。喜欢
$em->remove($entity);
$em->flush();
//-----------
$em->persist($entity);
$em->flush();
但这也行不通。
创建动作
/**
* Creates a new Booking entity.
*
* @Route("/create", name="booking_create")
* @Method("POST")
* @Template("TonsBookingBundle:Booking:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Booking();
$form = $this->createForm(new BookingType(), $entity);
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$room = $entity->getRoom();
if($room->getLocked() && $room->getLockedBy()->getId() === $this->getUser()->getId())
{
$entity->setCreatedAt(new \DateTime());
$entity->setUpdatedAt(new \DateTime());
$entity->setManager($this->getUser());
$em->persist($entity);
$room->setLocked(false);
$room->setLockedBy(null);
$room->setLockedAt(null);
$em->persist($room);
$em->flush();
return $this->redirect($this->generateUrl('booking_show', array('id' => $entity->getId())));
}
else
{
$form->addError(new FormError("Номер в текущий момент не заблокирован или заблокирован другим менеджером"));
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
更新操作
/**
* Edits an existing Booking entity.
*
* @Route("/edit/{id}/save", name="booking_update")
* @Method("PUT")
* @Template("TonsBookingBundle:Booking:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
/** @var $em EntityManager */
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('TonsBookingBundle:Booking')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Booking entity.');
}
$editForm = $this->createForm(new BookingType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('booking_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'form' => $editForm->createView(),
);
}