Cakephp 2.6
I have a Model, Temps, which has many tickets. In the index view of Temps I want to return for each record, the ticket with the date closest to the current date.
In mySQL it can be done as
'SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() ORDER BY expiry_date ASC LIMIT 1'
But I don't know how to run this as a sub query. My Current query to generate my results is as follows: (bearing in mind this has been configured for datatables) Tickets is an alias for the Upload Model
public function getAjaxIndexData($data) {
$tokens = explode(" ", $data['searchString']);
$conditions = array(
$this->alias . '.deleted' => false,
'OR' => array(
'CONCAT(' . $this->alias . '.first_name," ",' . $this->alias . '.last_name) LIKE' => '%' . implode(' ', $tokens) . '%',
),
$data['columnsFilter']
);
$fields = array(
'id',
'full_name',
'pps_number',
'mobile',
'email',
'start_date',
'time_served'
);
$order = array(
$data['orderField'] => $data['order']
);
$contain = array(
'LocalOffice.name',
);
$options = array(
'conditions' => $conditions,
'fields' => $fields,
'order' => $order,
'contain' => $contain,
'limit' => $data['limit'],
'offset' => $data['start']
);
$optionsNoFields = array(
'conditions' => $conditions,
'contain' => $contain,
);
$result['draw'] = $data['draw'];
$result['recordsTotal'] = $recordTotal = $this->find('count');
$result['recordsFiltered'] = $this->find('count', $optionsNoFields);
$result['data'] = $this->find('all', $options); //standard search
$result['data'] = $this->formatTable($result['data']);
return json_encode($result);
}
Within this query I would like to add a field that shows the nearest expiry date for each Temp.
How would I construct this?
Dynamically create a virtual field:
$this->virtualFields['nearest'] = '(SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() AND uploads.owner_id = '.$this->alias.'.ticket_id ORDER BY expiry_date ASC LIMIT 1')';
Then adjust your fields array
$fields = array(
'id',
'full_name',
'pps_number',
'mobile',
'email',
'start_date',
'time_served',
'nearest'
);
Also, the query could be rewritten as ("temp" needs to be replaced with the model alias)
SELECT MIN(expiry_date)
FROM uploads
WHERE expiry_date > CURDATE()
AND uploads.owner_id = temp.ticket_id;
Which means that a potentially better performing query would be to move that subquery out of the columns of the SELECT statement to a JOIN. For example:
SELECT *
FROM temp
LEFT JOIN (SELECT MIN(expiry_date) AS expiry,owner_id
FROM uploads
WHERE expiry_date > CURDATE())
GROUP BY owner_id) AS next_dates
ON next_dates.owner_id = temp.ticket_id;
Related
I am using Ci-bonfire and I want to give alias name of table when I have join multiple table at that time it will give column ambiguous so how to give alias name of table
Here is my code example..
$select = array(
$this->table_name . '.*',
'bf_countries.name'
);
$join = array(
'bf_countries' => array(
'condition' => 'bf_countries.country_id = ' . $this->table_name . '.country_id',
'type' => 'left'
)
);
$order = array(
"sortby"=>$this->table_name.".".$this->key,
"order"=>"DESC"
);
$config = array(
"req_data" => $req_data,
"select"=>$select,
"join"=>$join,
"order"=>$order
);
$this->grid->initialize($config);
return $this->grid->get_result();
Suppose I want to give alias name of bf_countries table so what to do for that..?
I have a find method that uses a DISTINCT clause to get results from my Model. The Controller code looks like below
$options = array(
'limit' => 10,
'fields' => array(
'DISTINCT id', 'title',
),
'contain' => array(
'Dealer' => array('id'),
),
'paramType' => 'querystring'
);
$this->Paginator->settings = $options;
$cars = $this->Paginator->paginate('Car'); // returns 6 distinct rows
The above query return 6 distinct rows and 12 total rows. So when I am displaying, the screen shows 6 distinct rows
However in the View, when I use
echo $this->Paginator->param('count'); // returns 12
I get a count of 12
I checked the SQL Log and noticed that the count query is not using the distinct clause. Any idea how I can override the Paginator count query to use the DISTINCT clause?
Found the solution,
In controller add distinct as an array parameter with other pagination options. So if I was trying to retrieve a list of Cars in my inventory with 10 cars at a time, the options would have a DISTINCT clause in the fields parameter and a separate parameter called distinct would also be added as shown below
$options = array(
'conditions' => $conditions,
'joins' => $joins,
'limit' => 10,
'fields' => array(
'DISTINCT Car.id', 'title', 'user_id'),
'contain' => array(
'Dealer' => array('id'),
),
'paramType' => 'querystring',
'distinct' => 'Car.id'
);
$this->Paginator->settings = $options;
$cars = $this->Paginator->paginate('Car');
In Model, use the below function to override the original paginateCount method
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$parameters = compact('conditions', 'recursive');
if (isset($extra['distinct'])) {
$parameters['fields'] = 'DISTINCT ' . $extra['distinct'];
$count = $this->find('count', array_merge($parameters, $extra));
} else {
// regular pagination
$count = $this->find('count', array_merge($parameters, $extra));
}
return $count;
}
No change in View
I am building an application using CakePHP and I am stuck on a problem retrieving data using a series of joins. In the simplified example below the join with the alias Delivery could have more than record and I want to bring back the record with a max value in a particular field in that table.
$inv_conditions = array( 'Invoice.invoice_date >=' => $DateFormatter->dateForDB($dateFrom),
'Invoice.invoice_date <=' => $DateFormatter->dateForDB($dateTo),
'Invoice.id >' => 385380 );
$join = array(array(
'table' => 'jobs',
'alias' => 'Jobs',
'type' => 'LEFT',
'conditions' => array('Invoice.job_id = Jobs.JOB_ID' )
),
array(
'table' => 'functional',
'alias' => 'Delivery',
'type' => 'LEFT'
'conditions'=> array('AND ' => array('Invoice.job_id = Delivery.JOB',
'Delivery.TYPE_STAGE = 1')
)
)
);
$invoices = $this->Invoice->find("all", array(
"fields" => array(
'Invoice.id',
'Invoice.job_id',
'Invoice.invoice_no',
'Invoice.consolidated_type',
'Invoice.customer_id_tbc',
'Invoice.invoice_date',
'Invoice.invoice_reference',
'Invoice.invoice_req',
'Jobs.PAYMENT_TYPE',
'Jobs.CUSTOMER',
'Jobs.MOST_RELEVANT_LINE',
'Delivery.DEPARTURE_DATE',
'Delivery.CNOR_CNEE_NAME',
'Delivery.TOWN_NAME',
),
"conditions" => $inv_conditions,
"joins" => $join
)
);
}
I can do this with SQL no problem as follows:
SELECT
jobs.JOB_ID,
jobs.CUSTOMER,
functional.JOB_LINE_ORDER,
functional.CNOR_CNEE_NAME,
functional.TOWN_NAME
FROM jobs JOIN functional ON
jobs.JOB_ID = 'M201409180267'
AND
functional.JOB = jobs.JOB_ID
AND
functional.TYPE_STAGE = 0
AND
functional.JOB_LINE_ORDER =
(SELECT MAX(JOB_LINE_ORDER) FROM functional
WHERE functional.JOB = 'M201409180267' AND functional.TYPE_STAGE = 0)
I have tried using the following to the conditions array:
'conditions' => array('AND ' =>
array( 'Invoice.job_id = Delivery.JOB',
'Delivery.TYPE_STAGE = 1'
'Delivery.JOB_LINE_ORDER = MAXIMUM(Delivery.JOB_LINE_ORDER)' )
)
This does bring back results but not the correct ones and the resulting SQL generated by Cake does have a select in the where clause. Is there a way of doing this when retrieving data in cake where the sql statement created will have a select in the where clause.
Any suggestions would be greatly appreciated.
Thanks
Bas
You need to use subquery to generate the select in the where clause. You can create a method in your model that does this and call it from your controller.
$subQuery = $db->buildStatement(
array(
'fields' => array(''),
'table' => $db->fullTableName($this),
'alias' => 'aliasName',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsArray,
'order' => null,
'group' => null
),
$this
);
$subQuery = ' <<YOUR MAIN QUERY CONDITION (' . $subQuery . ') >>';
$subQueryExpression = $db->expression($subQuery);
$conditions[] = $subQueryExpression;
return $this->Model->find('list', compact('conditions'));
I have two tables, User and Company. I have joining them like this:
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User'), array( 'id' => 'id',
'name' => 'User.name',
'gender' => 'User.gender',
'Company_id' => 'User.Company_id'
));
$select->join( 'Company', 'Company.id = User.Company_id',
array( 'Company_name' => 'Company.name' ,
'Company_address' => 'Company.address'
));
$rows = $table->fetchAll( $select );
It is working and giving me accurate result. Problem is that I have to mentions column names in above codes. I want to get all columns without mentioning them in above piece of code.
For example I want something like this that get all columns(But it is not providing all column values):
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User') );
$select->join( 'Company', 'Company.id = User.Company_id' );
$rows = $table->fetchAll( $select );
Thanks
Leaving away the second parameter to the from call should work: http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.columns
I've got a fairly modified pagination query using a number of Joins etc - but for some reason the paginator->counter() never matches the results from the count query.
You can see it in action at http://dev.qreer.com/ - by choosing various options on the LHS navigation, the query output is below and the paginator count appears to be pretty random.
Any idea where I can start looking to debug this?
In the Jobs Controller:
$this->paginate = $this->Job->paginateParams($data);
$jobs = $this->paginate('Job');
$this->set(compact('jobs'));
In the Model:
function paginateParams($data = null){
//lots of joins + conditions
return array('contain' => $contain, 'recursive' => 0,'joins' => $joins, 'conditions' => $conditions, 'group' => 'Job.id', 'order' => $order);
}
Sample Join (there's inner joins for all the join tables and data tables):
array(
'table' => 'education_backgrounds',
'alias' => 'EducationBackground',
'type' => 'INNER',
'conditions' => array('EducationBackgroundsJobs.education_background_id = EducationBackground.id'),
),
Sample Condition:
'EducationBackground.name' => array('Aerospace Engineering');
It's because of the group by I found a workaround. I'd love to put the link but i've lost it, so i'll post the code:
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$parameters = compact('conditions', 'recursive');
if (isset($extra['group'])) {
$parameters['fields'] = $extra['group'];
if (is_string($parameters['fields'])) {
// pagination with single GROUP BY field
if (substr($parameters['fields'], 0, 9) != 'DISTINCT ') {
$parameters['fields'] = 'DISTINCT ' . $parameters['fields'];
}
unset($extra['group']);
$count = $this->find('count', array_merge($parameters, $extra));
} else {
// resort to inefficient method for multiple GROUP BY fields
$count = $this->find('count', array_merge($parameters, $extra));
$count = $this->getAffectedRows();
}
} else {
// regular pagination
$count = $this->find('count', array_merge($parameters, $extra));
}
return $count;
}
I added it in the app_model and it works fine for me :)
Hope this helps
Edited: I found the link =)
http://wiltonsoftware.com/posts/view/custom-group-by-pagination-and-a-calculated-field
Figured it out:
The paginator counter relies on $this->find('count') to return an integer of the total of the results, which for some reason, doesn't like the 'group' parameter. So following the Custom Query Pagination (which also recommends at the bottom of the page to do the count yourself for any custom / modified pagination) - I added the following to my model:
function paginateCount(){
$params = Configure::read('paginate.params');
$params['fields'] = 'DISTINCT (Job.id)';
unset($params['group']);
unset($params['contain']);
unset($params['order']);
return $this->find('count', $params);
}
This overwrites the value with the correct one and it all seems to be working perfectly.
Bearing in mind I've added Configure::write('paginate', array('params' => $this->paginate['Job'])); to my controller so I can access the pagination parameters.
function paginateCount($conditions = null, $recursive = 0,$extra)
{
$db = $this->getDataSource();
$sql = $db->buildStatement(
array(
'fields' => array('DISTINCT Gdi.id'),
'table' => $db->fullTableName($this),
'alias' => 'Gdi',
'limit' => null,
'offset' => null,
'joins' => isset($extra['joins'])?$extra['joins']:null,
'conditions' => $conditions,
'order' => null,
'group' =>isset($extra['group'])?$extra['group']:null
),
$this
);
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
Just add this function in your model and change the field name and model name. Using this function you can customize you own query count.