0

Symfony2 と Doctrine2 の新機能として、エンティティ リポジトリにフォーム送信後にエンティティを検索する機能があります。入力は、$get['name'] = 'aname' のようなフォーム フィールドを含む配列 $get です。

私の問題は、ID、または ID と名前でリクエストすると、名前だけで問題なく、作成されたクエリに where 句がないため、すべてのエンティティが一致することです。

これが私のコードです:

public function search(array $get, $flag = False){
/* Indexed column (used for fast and accurate table cardinality) */
$alias = 'd';

/* DB table to use */
$tableObjectName = 'mysiteMyBundle:DB';

$qb = $this->getEntityManager()
  ->getRepository($tableObjectName)
  ->createQueryBuilder($alias)
  ->select($alias.'.id');

$arr = array();

//Simple array, will grow after problem solved
$numericFields = array(
   'id');

$textFields = array(
    'name');


while($el = current($get)) {
    $field = key($get);

    if ( $field == '' or $field == Null or $el == '' or $el == Null ) {
        next($get);
    }

    if ( in_array($field,$numericFields) ){
        if ( is_numeric($el) ){
            $arr[] = $qb->expr()->eq($alias.".".$field, $el);
        }
    } else {
        if ( in_array($field,$textFields) ) {
            $arr[] = $qb->expr()->like($alias.".".$field, $qb->expr()->literal('%'.$el.'%') );
        }
    }

    next($get);
}

if(count($arr) > 0) $qb->andWhere(new Expr\Orx($arr));
else unset($arr);

$query = $qb->getQuery();

if($flag)
  return $query;
else
  return $query->getResult();
}

名前 (「myname」など) のみを入力して生成されたクエリは次のとおりです。

SELECT d0_.id AS id0 FROM DB d0_

そのはず:

SELECT d0_.id AS id0 FROM DB d0_ WHERE d0_.name LIKE '%myname%'

私のコードの何が問題になっていますか?

ありがとう !

4

2 に答える 2

0

setParameterメソッドを使用する必要があります

$query->where('id = :id')->setParameter('id', $id);
于 2012-08-29T01:10:52.557 に答える
0

関連しているかどうかはわかりませんが、従来の「&&」や「||」とは意味が異なるため、「OR」または「AND」演算子は使用しないでください。cf http://php.net/manual/en/language.operators.logical.php

したがって、まず「AND」を「&&」に、「OR」を「||」に置き換えます。

于 2012-08-21T01:09:17.317 に答える