Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine/Symfony2 - DELETE FROM table WHERE field = "test"

I can't believe I can't seem to find this anywhere (without just forcing the entire SQL in). Docs talk about adding, searching, updating and removing an entity, but I just can't see how to do what this would be in pure SQL:

DELETE FROM table WHERE field = "test"

I'm guessing this just adds and updates, so I can't use this:

$product = new Product();

// etc.

$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();

and I don't think the 'remove' option would do it either:

$em->remove($product);
$em->flush();

So, can anyone point me in the right direction?

like image 615
user2143356 Avatar asked Jul 28 '13 17:07

user2143356


2 Answers

Search for the entity and remove it.

$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('MyBundle:Product');

/** @var $product Product */
$product = $repository->findOneBy(array('field' => 'test'));
$em->remove($product);
$em->flush();
like image 92
Emii Khaos Avatar answered Oct 17 '22 08:10

Emii Khaos


You can create a DQL query like this :

$query = $repository->createQuery('DELETE FROM entity e WHERE e.id = :id');
$query->setParameter('id', $id);
$query->execute();
like image 36
rpg600 Avatar answered Oct 17 '22 06:10

rpg600