I want to search data from table according to branch_id or date or in between dates.
What should be the Query in CakePHP.
Query in Controller:
$branchId = $_GET['data']['BranchDailyReport']['branch_id'];
$from_date = $_GET['data']['BranchDailyReport']['from_date'];
$to_date = $_GET['data']['BranchDailyReport']['to_date'];
$condition = array('OR' => array('BranchDailyReport.branch_id =' => $branchId,
'BranchDailyReport.date <= ' => $from_date,
'BranchDailyReport.date >= ' => $to_date
)
);
You should use the BETWEEN MySql operator
$condition = array('OR' => array('BranchDailyReport.branch_id =' => $branchId,
'BranchDailyReport.date BETWEEN ? AND ? ' => array($from_date, $to_date)
)
);
To find a date between two dates, that needs to be an AND. You could use an AND inside your OR condition to find between two dates:
$conditions = array(
'OR' => array(
'BranchDailyReport.branch_id =' => $branchId,
'AND' => array(
'BranchDailyReport.date <= ' => $from_date,
'BranchDailyReport.date >= ' => $to_date
)
)
);
By the looks of that form, you don't want "branch_id OR date OR in between dates" .. you might want branch_id AND in between dates"...
$conditions = array(
'BranchDailyReport.branch_id =' => $branchId,
'BranchDailyReport.date <= ' => $from_date,
'BranchDailyReport.date >= ' => $to_date
);
(side note) Also, if you're using CakePHP, you should be using $this->request->data
to access $_GET
variables. If you're in a model, than pass $this->request->data
as a function parameter.