CakePHP和查询

h79rfbju  于 2022-11-11  发布在  PHP
关注(0)|答案(2)|浏览(162)

我希望编写如下查询:

select * from products where id>5 and (cost>=100 and cost<=500)

我试过这个:

$lastid = $this->request->data("lastid");
$startPrice = $this->request->data("startPrice");
$endPrice = $this->request->data("endPrice");

$category = $this->request->data("category");

$conditions = array(
    'and' => array(
        array(                                      
            'Product.cost >= ' => $startPrice,                                  
            'Product.cost <= ' => $endPrice),
            array('Product.id > ' => $lastid,
                    'Product.category' => $category)
            )
);

这个人给我查询。我可以做什么来解决这个问题?

wydwbb8l

wydwbb8l1#

在查询中不需要AND选项,因为默认情况下它是AND选项,并且查询仅由“ands”组成

$conditions = array(                                 
    'Product.cost >= ' => $startPrice,                                  
    'Product.cost <= ' => $endPrice,
    'Product.id > ' => $lastid,
    'Product.category' => $category
);

编辑

如果您需要在category中使用OR语句,则只需添加:

$conditions = array(                                 
    'Product.cost >= ' => $startPrice,                                  
    'Product.cost <= ' => $endPrice,
    'Product.id > ' => $lastid,
    'OR' => array(
        'Product.category' => $category,
        'Product.category' => anoter_value
    )
);
nom7f22z

nom7f22z2#

您可以在cakephp查询中不包含和的情况下执行此操作。复制代码并尝试执行,尝试查看此代码与您的代码的差异

$lastid = $this->request->data["lastid"];
$startPrice = $this->request->data["startPrice"];
$endPrice = $this->request->data["endPrice"];
$category = $this->request->data["category"];

$conditions = array(                                
            'Product.cost >= ' => $startPrice,                                  
            'Product.cost <= ' => $endPrice,
            'Product.id > ' => $lastid,
             'Product.category' => $category
);

$result = $this->YourModel->find('all', array('conditions' => $conditions));

相关问题