dtftao7249656 2017-11-12 19:47
浏览 82
已采纳

如何使用Doctrine绑定动态值

I have an array of parameters wich I use to bind values in my query.

$params = [
            'brandFilter' => $articles['brands'],
            'categoryFilter' => $articles['categories'],
            'priceFromFilter' => $articles['prices']['from'],
            'priceToFilter' => $articles['prices']['to'],
        ];

My problem is that sometimes one or several of these parameters can be empty because it depends on what the user has checked.

I can do my queries using if !empty but it quickly becomes ugly to write and read, as following :

$qb = $this->createQueryBuilder('a');
        $qb->select('a');

if (!empty($articles['brands']) && !empty($articles['categories']) && !empty($articles['prices']['from']) && !empty($articles['prices']['to'])) {

    $qb->where('a.brand IN (:brandFilter)')
       ->andWhere('a.category IN (:categoryFilter)')
       ->andWhere('a.price BETWEEN :priceFromFilter AND :priceToFilter')
       ->setParameters($params);
}

elseif (!empty($articles['brands']) && !empty($articles['categories'])) {
   $this->findByBrandsAndCategories($qb, $articles);

} elseif (!empty($articles['brands']) && empty($articles['categories'])) {
   $this->findByBrands($qb, $articles);

} elseif (!empty($articles['categories']) && empty($articles['brands'])) {
   $this->findByCategories($qb, $articles);
}

return $qb->getQuery()->getArrayResult();
    }

It's really long to write and I was wondering if anyone had another solution than going through condition blocks ?

  • 写回答

1条回答 默认 最新

  • douwen3836 2017-11-12 20:31
    关注

    I think generating the query as follows could suit your needs:

    $qb = $this->createQueryBuilder('a');
    
    if (!empty($articles['brands'])) {
        $qb
            ->andWhere('a.brand IN (:brandFilter)')
            ->setParameter('brandFilter', $articles['brands']);
    }
    
    if (!empty($articles['categories'])) {
        $qb
            ->andWhere('a.category IN (:categoryFilter)')
            ->setParameter('categoryFilter', $articles['categories']);
    }
    
    if (!empty($articles['prices']['from'])) {
        $qb
            ->andWhere('a.price >= (:priceFromFilter)')
            ->setParameter('priceFromFilter', $articles['prices']['from']);
    }
    
    if (!empty($articles['prices']['to'])) {
        $qb
            ->andWhere('a.price <= (:priceToFilter)')
            ->setParameter('priceToFilter', $articles['prices']['to']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?