Symfony 2 - Doctrine 2 - Native Sql - Delete Query
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,
as per Doctrine 2 Native SQL documentation page:
If you want to execute DELETE, UPDATE or INSERT statements the Native SQL API cannot be used and will probably throw errors.
You can user DQL queries instead.
$query = $em->createQuery("DELETE FROM YourNamespace\YourBundle\Entity\YourEntity e WHERE e.fieldone_id = " .$fieldoneid . " AND e.fieldtwo_id = " . $fieldtwoid);
$query->execute();
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