Reputation: 726
I want to fetch rows following filters passed by POST to my Controller, but the parameters are optional and sometimes they could be empty, and the rule is: whenever a field is passed empty, fetch all rows ( dont filter ).
I can do this in raw sql:
SELECT * from users where id = $param OR $param IS NULL
But I dont know how to do this CakePHP way. Tried a lot of combinations. My present stage is some like:
[...]
'conditions' => array(
array(
'OR' => array(
'Request.id' => $this->request->data['Search']['id'],
),
Basically, I dont know how to do the 'OR $param IS NULL' part of the query. In the present conditions, I can sucefully fetch rows when I pass a 'id' param from the view, but if I dont pass anything ( null ID ), the result is 0 rows, and should be all rows.
I'm using Postgres as SGBD.
Thanks
EDIT WITH SOLUTION
Following the idea of @Vin000, I can do:
$conditions = array();
if(isset($this->request->data['Search']['id'] ) and $this->request->data['Search']['id'] != null )
{
$conditions['Request.id'] = $this->request->data['Search']['id'];
}
which solves my problem.
Upvotes: 0
Views: 870
Reputation: 4645
You should use $this->request->params or $this->params->query if you're passing your data from the URL. You can't access data in $this->request->post if you're sending it from URL. Please add few conditions like as below.
$conditions = array();
if (!empty($this->params->query['keywords']))
$conditions[] = array($this->params->query['search_by'] . ' like' => "%" . $this->params->query['keywords'] . "%");
if (!empty($this->request->params['pass']))
$conditions[] = //Your conditions
I personally suggest you to pass query parameters from URL so you can know that what the values are and for which parameter.
Upvotes: -1