随机更新一定数量的行

时间:2016-04-24 09:35:02

标签: symfony doctrine query-builder

我试图更新我的实体的一定数量的行" 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'));
}

但是上面的代码更新了我数据库的所有行。我只需要更新两行。有什么帮助吗?

2 个答案:

答案 0 :(得分: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'));

}

使用上述代码,我希望您只能更新 两行 行和 随机

祝你好运!

答案 1 :(得分:0)

虽然Houssem Zitoun suggested之类的解决方案可能有效,但为什么不使用子查询呢?

如果你得到了(就像我做的那样,如果没有,只需跳过中间SELECT

  

错误:#1235 - 此版本的MySQL尚不支持'LIMIT& IN / ALL / ANY / SOME子查询'

使用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