Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 - Doctrine 2 - Native Sql - Delete Query

Instead of removing my entities one by one with

$this->em->remove($price);

I would like to execute a native SQL query to delete all my entities.

Here is what I tried :

$sqlQuery = "delete from mytable where mytable.fieldone_id = ".$fieldoneid." and mytable.fieldtwo_id = ".$fieldtwoid.";";

$query = $this->getEntityManager()->createNativeQuery($sqlQuery);

$query->execute();

It returns the following error :

Catchable fatal error: Argument 2 passed to Doctrine\ORM\EntityManager::createNativeQuery() must be an instance of Doctrine\ORM\Query\ResultSetMapping, none given

It wants me to pass a ResultSetMapping, but it is a delete query...

Can anyone please teach me how to do it?

like image 336
BENARD Patrick Avatar asked Jan 08 '14 16:01

BENARD Patrick


2 Answers

If you want to use the native way in doctrine, you can use in the entity repository :

public function deleteUserNative(User $user): void
{
    $this->getEntityManager()->getConnection()->delete('user', array('id' => $user->getId()));
}

And just call this in your controller :

$em->getRepository(User::class)->deleteUserNative($user);

Regards,

like image 138
Yohann Daniel Carter Avatar answered Sep 28 '22 00:09

Yohann Daniel Carter


I use a different way of executing native SQL queries that is much easier, in my opinion. Try something like this (I am also using the PDO method of including variables in the query, which is safer):

$sql = "delete from mytable where mytable.fieldone_id = :fieldoneid and mytable.fieldtwo_id = :fieldtwoid";
$params = array('fieldoneid'=>$fieldoneid, 'fieldtwoid'=>$fieldtwoid);

$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($params);
// if you are doing a select query, fetch the results like this:
// $result = $stmt->fetchAll();

This works great for me, hope it helps

like image 30
Sehael Avatar answered Sep 28 '22 00:09

Sehael