2014-07-10 12 views
7

Desidero aumentare un valore nella mia entità dottrina.
Attualmente lo sto facendo in questo modo.Documento Valore incremento entità (contatore download)

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

C'è modo di eseguire qualcosa di simile in dottrina:

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

EDIT:

Il problema nell'esempio dottrina di cui sopra è che tra il carico e filo è il tempo in cui gli altri potrebbe scaricare il file e quindi il contatore non è corretto.

risposta

7

È anche possibile effettuare le seguenti operazioni in un repository di entità:

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

o utilizzando DQL:

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

o attraverso un DQL semplificata:

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

Lo svantaggio di queste soluzioni: se la tua entità era già stata caricata, avrà il conteggio precedente e non il conteggio incrementato.

Il modo in cui l'hai fatto è perfetto, ma un modo migliore è aggiungere un metodo di incremento alla tua entità.

+0

Grazie, il tuo DQL mi ha aiutato. invece di usare ': downloadCounter' ho usato' f.downloadCounter + 1' e ho aggiunto un file per il file ID –

+0

L'ho aggiunto come esempio - felice la mia risposta è stata utile –

+6

questa non è una risposta, la domanda è come fare query incrementale, non come sommare il valore con +1 –

3

Si potrebbe semplicemente aggiungere un metodo di incremento al modello.

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

Questo approccio fallirà quando ci saranno due richieste in meno simultanee - l'incremento verrà eseguito solo una volta. – Casey

+0

Predisposto per condizioni di gara. – Kaspars

Problemi correlati