【问题标题】:cakephp pagination with AND OR condition inside loop循环内带有AND OR条件的cakephp分页
【发布时间】:2017-07-26 09:12:42
【问题描述】:

我正在使用 cakephp 分页我正在使用 2 组复选框来过滤 ma​​terialtypeoccasion 所以我编写了以下代码

public function index($category) {

if(!empty($this->params['url']['data']['filter']['materialtype']))
{
foreach ($this->params['url']['data']['filter']['materialtype'] as $v){
$conditions1[] ="(Product.materialtype LIKE '%$v%')";
}
$conditions[] = implode(' OR ', $conditions1);
}

if(!empty($this->params['url']['data']['filter']['occasion']))
{
foreach ($this->params['url']['data']['filter']['occasion'] as $v){
$conditions2[] ="`Product`.`occasion` LIKE '%$v%'";
}
$conditions[] = implode(' OR ', $conditions2);
}

}

我的以下代码正在生成这个 sql 查询

SELECT `Product`.`id`, `Product`.`category`, `Product`.`name`, FROM mydb`.`products` AS `Product` WHERE `Product`.`category` = 'Necklace' AND (`Product`.`materialtype` LIKE '%Yellow Gold%') OR (`Product`.`materialtype` LIKE '%White Gold%') AND (`Product`.`occasion` LIKE '%Traditional%') OR (`Product`.`occasion` LIKE '%Modern%')

但我正在寻找这个输出。

SELECT `Product`.`id`, `Product`.`category`, `Product`.`name`, FROM mydb`.`products` AS `Product` WHERE `Product`.`category` = 'Necklace' AND ((`Product`.`materialtype` LIKE '%Yellow Gold%') OR (`Product`.`materialtype` LIKE '%White Gold%')) AND ((`Product`.`occasion` LIKE '%Traditional%') OR (`Product`.`occasion` LIKE '%Modern%'))

【问题讨论】:

    标签: pagination cakephp-2.0


    【解决方案1】:

    您需要从 foreach 内的内部语句中删除内括号。并将其添加到外部,如下所示。

    if(!empty($this->params['url']['data']['filter']['materialtype']))
    {
           foreach ($this->params['url']['data']['filter']['materialtype'] as $v){
                $conditions1[] = "Product.materialtype LIKE '%$v%'";
           }
           $str_cond = implode(' OR ', $conditions1);
           $conditions[] = '(' . $str_cond . ')';
    }
    
    if(!empty($this->params['url']['data']['filter']['occasion']))
    {
        foreach ($this->params['url']['data']['filter']['occasion'] as $v){
            $conditions2[] = "Product.occasion LIKE '%$v%'";
        }
        $str_cond = implode(' OR ', $conditions2);
        $conditions[] = '(' . $str_cond . ')';
    }
    

    【讨论】:

    • 你的代码帮助了我,但它完全不起作用我刚刚更新了我的问题,你能回来看看吗。
    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多