dongwu5318 2012-02-14 20:27
浏览 88
已采纳

Doctrine DQL条件查询

I'm trying to build a dynamic query with Doctrine's query builder. Let's say I'd also like to optionally select an end time in the following (only if one was entered). How would I add this conditionally to the statement?

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

1条回答 默认 最新

  • douhuo1738 2012-02-16 15:58
    关注

    I'd do something like this:

    // 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题