2012-02-14 19 views
2

Doctrineのクエリビルダを使用して動的クエリを作成しようとしています。また、次の中で終了時刻を選択することもできます(入力した場合のみ)。この条件に文にどのように追加しますか?Doctrine DQL条件付きクエリ

$query = $this->getEntityManager()->createQueryBuilder() 
     ->select('m') 
     ->from($this->getEntityName(), 'm') 
     ->where("m.start > '" . date('Y-m-d H:i:s', strtotime($start)) . "'") 
     ->getQuery(); 

答えて

5

私はこのような何かをしたい:

// first, create the query builder 
$qb = $this->getEntityManager()->createQueryBuilder() 
    ->select('m') 
    ->from($this->getEntityName(), 'm') 
; 

// add the default condition 
$conditions = array(
    $qb->expr()->gt('m.start', date('Y-m-d H:i:s', strtotime($start))); 
); 

// put your condition here 
if (isset($end)) { 
    $conditions[] = $qb->expr()->lt('m.end', date('Y-m-d H:i:s', strtotime($end))); 
} 

// convert the conditions to an AND clause 
$conditions = call_user_func_array(array($qb, 'andX'), $conditions); 

// add the WHERE clause 
$qb->where($conditions); 

// get the query 
$query = $qb->getQuery(); 
+2

これは動作します。ありがとう!しかし、次のようにする必要があります。$ conditions = call_user_func_array(array($ qb-> expr()、 'andx')、$ conditions); –