2016-04-24 120 views
0

我正在嘗試更新我的實體「Vehicule」的某些行數。我不知道它是如何工作的。 我實際上只想修改direction = 5的兩行。這是我用來更新的函數。隨機更新某些行數

public function ValidAction(\OC\UserBundle\Entity\User $direction) { 

    $qb = $this->getDoctrine() 
     ->getRepository('CarPfeBundle:Vehicule') 
     ->createQueryBuilder('v'); 

    $q = $qb->update ('CarPfeBundle:vehicule v') 
      ->set('v.direction', '?1') 
      ->where('v.direction = ?2') 
      ->setParameter(1, $direction) 
      ->setParameter(2, 5) 
      ->getQuery(); 

     $p = $q->execute(); 

    return $this->redirect($this->generateUrl('demandeveh_afficher')); 
} 

但上面的代碼更新我的數據庫的所有行。我只需要更新兩行。請幫忙嗎?

+0

您可以指定請問行的ID號?我想要更新的行數爲 –

+0

?其實它是隨機的,我只需要更新任何兩個隨機的行,這是足夠的where語句。我一直在嘗試使用「update top(2)..」,但它不起作用 –

+0

如果是這樣,嘗試隨機找到任何2個車輛:$ q = $ qb-> find($ vehiculeId);並修改這些Vehicule –

回答

0

試着做到這一點;

public function ValidAction(\OC\UserBundle\Entity\User $direction) { 

    $qb = $this->getDoctrine() 
       ->getRepository('CarPfeBundle:Vehicule') 
       ->createQueryBuilder('v'); 

    // $ids an array that contains all ids with your condition 
    $ids = $qb->select('v.id') 
       ->where('v.direction = :direction') 
       ->setParameter(
        array(
         'direction' => $direction 
        ) 
       ) 
       ->getQuery() 
       ->getResult(); 

    $id1 = $ids[array_rand($ids)]; 
    $id2 = $ids[array_rand($ids)]; 

    //To be sure that $id1 is different from id2 
    while ($id1 == $id2) { 
     $id2 = $ids[array_rand($ids)]; 
    } 


    $q = $qb->update ('CarPfeBundle:vehicule v') 
      ->set('v.direction', ':val1') 
      ->where('v.direction = :val2') 
      ->andWhere('v.id IN (:id1, :id2)') 
      ->setParameter(
       array(
        'val1' => $direction , 
        'val2' => 5 , 
        'id1' => $id1, 
        'id2' => $id2, 
       ) 
      ) 
      ->getQuery(); 

    $p = $q->execute(); 

return $this->redirect($this->generateUrl('demandeveh_afficher')); 

}

與上面的代碼,我希望你可以更新只有兩隨機

祝你好運!

+0

@Eya Behi,它的工作? –

0

雖然像Houssem Zitoun suggested這樣的解決方案可能工作,爲什麼不使用子查詢?

如果你得到的(像我一樣,如果沒有,就跳過中間SELECT

Error: #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

this answer和類似(doc): - 未經測試的

UPDATE CarPfeBundle:Vehicule v 
    SET v.direction = ?1 
    WHERE v.direction IN 
    (SELECT * FROM (
     SELECT v.direction 
     FROM CarPfeBundle:Vehicule v2 
     WHERE v.direction = ?2 LIMIT 2 
    )) AS sq