问题
I am using Symfony2, i must use the Doctrine QueryBuilder ( http://docs.doctrine-project.org/en/latest/reference/query-builder.html ) The documentation does not have an example for the delete or update statement.
My entity is :
object(stdClass)[417]
public '__CLASS__' => string 'Les\DataBundle\Entity\News' (length=26)
public 'id' => int 1
public 'restoId' => int 1
public 'category' => string 'dessert' (length=7)
public 'text' => string 'jlkdjsalkdj sa' (length=14)
public 'dateCreated' => string 'DateTime' (length=8)
public 'dateModified' => null
I am trying to delete a row in the database, but i keep getting the error:
[Semantical Error] line 0, col 7 near 'News WHERE n.id': Error: Class 'News' is not defined.
My query is :
$newsID =2 ;
$qd = $repository->createQueryBuilder('n');
$qd->delete('n')
->where('n.id = :id')
->setParameter('id',$newsID);
$query = $qd->getQuery();
$result = $query->getResult();
And would the update statement have the same structure?
回答1:
For the delete statement is different from the select, you don't specify the column name for the delete unlike select.
Corrected Code
$qd = $repository->createQueryBuilder('n');
$qd->delete()
->where('n.id = :id')
->setParameter('id',$newsID);
$query = $qd->getQuery();
$result = $query->getResult();
Another Format
$query = $this->getDoctrine()->getManager()->createQuery('delete FROM LesDataBundle:News n where n.id = '.$newsID);
$result = $query->getResult();
For the Update Statement it is :
$qd = $repository->createQueryBuilder('n');
$qd->delete()
$qd->update()
->set('n.text' , ':text')
->where('n.id = :id')
->setParameters( array('id'=> $newsID, 'text' => 'Hello World') );
$query = $qd->getQuery();
$result = $query->getResult();
来源:https://stackoverflow.com/questions/24212370/doctrine-query-builder-delete-statement