Doctrine update query with LIMIT

假如想象 提交于 2019-12-10 10:47:03

问题


I would like to do an update-query with a LIMIT like that:

UPDATE anytable SET anycolumn = 'anyvalue' WHERE anothercolumn='anothervalue' LIMIT 20

How is this possible with doctrine 2.1 ?


回答1:


Not doctrine specific, but maybe possible with a subquery ?

UPDATE messages SET test_read=1
 WHERE id IN (
     SELECT id FROM (
         SELECT id FROM messages 
         ORDER BY date_added DESC  
         LIMIT 5, 5
     ) tmp
 );



回答2:


I found I had to fetch the connection from the entityManager and call executeUpdate:

$em->getConnection()->executeUpdate(
    "UPDATE anytable SET anycolumn = 'anyvalue'
     WHERE anothercolumn='anothervalue'
     LIMIT 20");

The doctrine page about native queries says:

If you want to execute DELETE, UPDATE or INSERT statements the Native SQL API cannot be used and will probably throw errors. Use EntityManager#getConnection() to access the native database connection and call the executeUpdate() method for these queries.




回答3:


EDIT:

you can go about it in 2 different ways:

1 - Create query directly using DQL:

$query = $entityManager->createQuery('UPDATE Entities\User u SET u.someValue = newValue WHERE u.id = someId');

// this will add the LIMIT statement
$query->setMaxResults(20);

$query->execute();

2 - Create query using QueryBuilder:

$qb = $this->_em->createQueryBuilder();

$query = $qb->update('Entities\User', 'u')
            ->set('u.someValue', newValue)
            ->where('u.id = someId')
            ->getQuery();

// this will add the LIMIT statement
$query->setMaxResults(20);   

$query->execute();

you should do: echo $query->getSQL(); to check out the sql generated for these two

EDIT: another alternative (not highly recommended) is to use Native SQL



来源:https://stackoverflow.com/questions/8893234/doctrine-update-query-with-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!