2014-07-10 20 views
7

我想在我的教條實體中增加一個值。
目前我正在這樣做。主義實體增加值(下載計數器)

$file->setDownloadCounter($file->getDownloadCounter() + 1); 
$em = $this->getDoctrine()->getManager(); 
$em->persist($fileVersion); 
$em->flush(); 

有沒有辦法在教義來執行這樣的事情:

UPDATE file SET downloadCounter = downloadCounter + 1 WHERE id = 1 

編輯:

在上面的學說例子的問題是,加載和沖洗之間的時間在別人可以下載該文件,因此計數器不正確。

回答

7

您也可以在實體存儲庫中的以下內容:

return $this 
    ->createQueryBuilder('f') 
    ->update($this->getEntityName(), 'f') 
    ->set('f.downloadCounter', $file->getDownloadCounter() + 1) 
    ->where('f.id = :id')->setParameter('id', $file->getId()) 
    ->getQuery() 
    ->execute(); 

或者使用DQL:

$em = $this->getDoctrine()->getManager(); 
$query = $em->createQuery(
    'UPDATE YourBundle:File f 
     SET f.downloadCounter = :downloadCounter' 
)->setParameter('downloadCounter', $file->getDownloadCounter() + 1); 

或者通過簡化的DQL:

$em = $this->getDoctrine()->getManager(); 
$query = $em->createQuery(
    'UPDATE YourBundle:File f 
     SET f.downloadCounter = f.downloadCounter + 1' 
); 

這些解決方案的缺點:如果您的實體已經加載,它將具有先前的計數,而不是遞增的計數。

你做的方式非常好,但更好的方法是將增量方法添加到實體。

+0

謝謝你,你的DQL幫助了我。而不是使用':downloadCounter'我沒有使用'f.downloadCounter + 1'並添加了一個文件的位置 –

+0

我已經添加它作爲示例 - 很高興我的回答有幫助 –

+6

這不是一個答案,問題是如何使增量查詢,而不是如何用+1代替summ值 –

3

您可以簡單地將增量方法添加到模型中。

class File { 
    public function increaseDownloadCounter() 
    { 
     $this->downloadCounter++; 
    } 
} 
-1
$em = $this->getDoctrine()->getManager(); 

$entity = $em->getRepository('AcmeDemoBundle:EntityName')->find($entityId); 
$valueToIncrement = $entity->getMyField(); // where MyField is the DB field to increment 
$entity->setMyField(++$valueToIncrement); 

$em->persist($entity); 
$em->flush(); 
+0

當有兩個同時發生的請求時,這種方法會失敗 - 增量只能進行一次。 – Casey

+0

適應比賽條件。 – Kaspars