Pregunta

I wish to write a query like:

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

I tried this:

$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)
            )
);

This one is giving me in query. What can I do to resolve this?

¿Fue útil?

Solución

You don't need the AND option in your query, as it is by default, and your query is only composed with 'ands'

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

EDIT

If you need an OR statement in category then you can just add:

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

Otros consejos

You can do this without including and in cakephp query. Copy the code and try it and try to see the difference of this and your code

$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));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top