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%'
私のコードの何が問題になっていますか?
ありがとう !