findall ignoring order parameter? - cakephp

I'm trying to use the following:
$this->Chapter->recursive=1;
$chaps = $this->Chapter->find('all', array(
'order'=> array('sequence_number' => 'ASC')
));
$this->set('chapters', $chaps );
to retrieve all my chapters by increasing order, but CakePHP seems to be ignoring the 'order' parameter. I believe that I have the syntax correct (based on view-source:http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types, which says the following should work:
public function index() {
$articles = $this->Article->find('available', array(
'order' => array('created' => 'desc')
));
}
). The SQL for the table looks like:
CREATE TABLE chapters (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sequence_number INT UNSIGNED,
title VARCHAR(50)
);
and I'm not getting any syntax or run-time errors. However, the SQL generated by Cake to actually get the chapter records is:
SELECT `Chapter`.`id`, `Chapter`.`sequence_number`, `Chapter`.`title`
FROM `Tutorial`.`chapters` AS `Chapter` WHERE 1 = 1
Clearly I'm doing something wrong, but I don't know what it is.
As a work-around I'm happy to put an order property on the Model. Since I typically want to retrieve chapters by sequence number I'm fine with adding this to the model:
public $order = 'Chapter.sequence_number ASC';
Once I do that Cake generates
SELECT `Chapter`.`id`, `Chapter`.`sequence_number`, `Chapter`.`title`
FROM `Tutorial`.`chapters` AS `Chapter` WHERE 1 = 1
ORDER BY `Chapter`.`sequence_number` ASC

What if you try something like this, instead:
$chaps = $this->Chapter->find('all', array(
'order' => array('Chapter.sequence_number ASC')
));
The main difference being this part: Chapter.sequence_number ASC

Related

CakePHP count query gives different result when run in phpmyadmin

I am running the following query on my database:-
SELECT COUNT(*) AS COUNT, `Doctor`.`device_type` FROM `doctors` AS `Doctor` WHERE 1 = 1 GROUP BY `Doctor`.`device_type`
and it gives the result:-
count device_type
47 Android
23 iPhone
Whereas when running this query as a CakePHP query it gives the result as '2':-
$this->Doctor->find('count',array('group'=>'Doctor.device_type'));
Can anyone please suggest why this is happening?
The CakePHP result is correct as it is returning a count of the number of results returned by your query. In your case you have 2 rows: 'Android' and 'iPhone'.
find('count') always returns an integer, not an array. What Cake is doing is basically this:-
$data = $this->Doctor->find('all', array('group' => 'Doctor.device_type'));
$count = count($data); // This is what find('count') will return.
You need to do something like the following instead:-
$data = $this->Doctor->find('all', array(
'fields' => array(
'Doctor.device_type',
'COUNT(Doctor.*) AS count'
)
'group' => 'Doctor.device_type'
));

cakePHP :Find all query conditions questions

I'm trying to format a find condition to generate a set of data to be later printed to an excel view via PhPExcel. The intended functionality is that if the start_date and the end_date fields match for the entry, the entry is included in the array. If the fields do not match, it's excluded.
$my_data = $this-> RecordsMaster-> find("all", array(
'conditions' => array(
"RecordsMaster.start_date" == "RecordsMaster end_date"
)
));
The problem lies in the fact that the statement above doesn't actually do anything. Rows from mySQL table with start and end dates that differ are included in the data dump to excel.
The conditions in the question don't mean much
The conditions in the question are equivalent to:
$my_data = $this-> RecordsMaster-> find("all", array(
'conditions' => array(
false
)
));
Which will return no records, since it will generate the following sql:
WHERE 0;
Don't use key => value to match fields
Correcting the typos in the code in the question would still not generate desired sql - it would generate:
WHERE `RecordsMaster`.`start_date` = "RecordsMaster end_date"
I.e. where start_date is that litteral string.
The intended functionality is that if the start_date and the end_date fields match for the entry
To generate WHERE field = otherfield you can specify as a string:
$my_data = $this-> RecordsMaster-> find("all", array(
'conditions' => array(
"RecordsMaster.start_date = RecordsMaster.end_date"
)
));

CakePHP find joined records with conditions on each table

I want to see all the records from a join, setting a WHERE condition on each side of the join.
For example, I have LOAN and BORROWER (joined on borrower.id = loan.borrower_id). I want the records where LOAN.field = 123 and BORROWER.field = 'abc'.
The answers here (this one, for example) seem to say that I should use Containable.
I tried that. Here's my code:
$stuff = $this->Borrower->find('all', array(
'conditions' => array(
'Borrower.email LIKE' => $this->request->data['email'] // 'abc'
),
'contain'=>array(
'Loan' => array(
'conditions' => array('Loan.id' => $this->request->data['loanNumber']) // 123
)
)
));
I expected to have a single result because in my data, there is only one joined record with both of those conditions. Instead, I get two results,
Result 1 is {Borrower: {field:abc, LOAN: {field: 123} } // correct
Result 2 is {Borrower: {field:abc, LOAN: {NULL} } // incorrect
When I look at the SQL that CakePHP used, I don't see a join. What I see is two separate queries:
Query 1: SELECT * from BORROWER // (yielding 2 IDs),
Query 2: SELECT * FROM LOAN WHERE borrower_id in (IDs)
This is not what I want. I want to join the tables, then apply my conditions. I could easily write the SQL query, but am trying to do it the Cake way since we've adopted that framework.
Is it possible?
Try to do something like this:
$options['conditions'] = array(
'Borrower.email LIKE' => $this->request->data['email'] // 'abc',
'loan.field' => '123' )
$options['joins'] = array(
array('table' => 'loans',
'alias' => 'loan',
'type' => 'INNER',
'conditions' => array(
'borrower.id = loan.borrower_id')
)
);
$options['fields'] = array('borrower.email', 'loan.field');
$test = $this->Borrower->find('all', $options);
You should see a SQL statement like:
SELECT borrower.email, loan.field
FROM borrowers AS borrower
INNER JOIN loans AS loan
ON borrower.id = loan.borrower_id
AND loan.field = '123'
WHERE borrower.email = 'abc'
Your results will be in an array
{Borrower: {field:abc} LOAN: {field: 123} }
You will find more information in this document.
I think I'll accept Jose's answer because it's exactly what I want. But I did notice that I didn't need any fancy tricks -- no joins or contains -- if I used the other model as my starting point.
A Borrower hasMany Loans, and a Loan belongsTo a Borrower. Using Loan as my model, Cake will automatically join the tables, but not using Borrower.
$this->Loan->find('all', array( // Not $this->Borrower->find() !
'conditions' => array(
'Borrower.field' => 'abc',
'Loan.field' => 123
)
));

CakePHP Search between 2 Date Records

I am building a small Web App that lets users reserve Office Rooms and Equipment. For the Reservation they enter a Start and an End Date.
When a user tries to find out if any (for example) car is available on 2012-10-23, and the database holds reservation date records of Start: 2012-10-20 and End: 2012-10-25 for (lets say) all the cars, how do I include all the dates between my date entries in the search?
The $date variable gets it's value from the Date Search Form Field.
This, unfortunately does not work, and I can't figure out how to use daysAsSql for this query:
$conditions = array(
'conditions' => array(
'? BETWEEN ? AND ?' => array($date,'Equipment.date_start','Equipment.date_end'),
)));
$this->set('equipments', $this->Equipment->find('all', $conditions));
There is a simpler solution to this, but thanks for the help:
(As a condition in the find:)
array('Equipment.date_start <= ' => $date,
'Equipment.date_end >= ' => $date
),
In case if you have one date and you want to use BETWEEN
$date_start = start date;
$date_end = date_end;
$conditions = array(
'conditions' => array(
'date(Equipment.create) BETWEEN ? AND ?' => array($date_start, $date_end),
)));
$this->set('equipments', $this->Equipment->find('all', $conditions));
This is the case if you have From AND To
in your case
$date_start = start date;
$date_end = date_end;
$conditions = array(
'conditions' => array(
'Equipment.start_date >=' => array($date_start),
'Equipment.end_date <=' => array($date_end)
));
$this->set('equipments', $this->Equipment->find('all', $conditions));
Here is CakePHP BETWEEN query example.
I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:
// just return these two fields
$fields = array('uri', 'page_views');
// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));
// run the "select between" query
$results = $this->Event->find('all',
array('fields'=>$fields,
'conditions'=>$conditions));
Ref from
$start = date('Y-m-d');
$end = date('Y-m-d', strtotime('+1 month'));
$conditions = array('Event.start <=' => $end, 'Event.end >=' => $start);
$this->Event->find('all', array('conditions' => $conditions));
If you are on cakephp 2.0 this is the answer http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::daysAsSql
If you are on cakephp 1.3 you can use TimeHelper, just import it and use the same function as per example in documentation here http://book.cakephp.org/1.3/en/view/1471/Formatting
You cannot use database columns with this BETWEEN-syntax. If you assign strings in the array, CakePHP will quote them. Same for numeric values depending on your database setup.
CakePHP will quote the numeric values depending on the field type in your DB.
– see http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions
If you still want to use the BETWEEN, you can write your queries into the array key because CakePHP will not escape the keys, but only the values.
CakePHP only escapes the array values. You should never put user data into the keys. Doing so will make you vulnerable to SQL injections.
– see http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions
Concerning your problem:
$this->Model->find('all', array(
'conditions' => array(
'"YYYY-MM-DD" BETWEEN Model.date_start AND Model.date_end',
),
));
You can even work with MySQL date and time functions:
$this->Model->find('all', array(
'conditions' => array(
'CURDATE() BETWEEN Model.date_start AND Model.date_end',
),
));
If you use date/time functions, do not quote them. If you use a specific date put it in quotes.

Paginate results filtered by condition on associated model (HABTM) using Containable

I need to paginate list of Products belonging to specific Category (HABTM association).
In my Product model I have
var $actsAs = array('Containable');
var $hasAndBelongsToMany = array(
'Category' => array(
'joinTable' => 'products_categories'
)
);
And in ProductsController
$this->paginate = array(
'limit' => 20,
'order' => array('Product.name' => 'ASC'),
'contain' => array(
'Category' => array(
'conditions' => array(
'Category.id' => 3
)
)
)
);
$this->set('products', $this->paginate());
However, resulting SQL looks like this:
SELECT COUNT(*) AS `count`
FROM `products` AS `Product`
WHERE 1 = 1;
SELECT `Product`.`*`
FROM `products` AS `Product`
WHERE 1 = 1
ORDER BY `Product`.`name` ASC
LIMIT 20;
SELECT `Category`.`*`, `ProductsCategory`.`category_id`, `ProductsCategory`.`product_id`
FROM `categories` AS `Category`
JOIN `products_categories` AS `ProductsCategory` ON (`ProductsCategory`.`product_id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) AND `ProductsCategory`.`category_id` = `Category`.`id`)
WHERE `Category`.`id` = 3
(I.e. it selects 20 Products and then queries their Categories)
while I'd need
SELECT COUNT(*) AS `count`
FROM `products` AS `Product`
JOIN `products_categories` AS `ProductsCategory` ON `ProductsCategory`.`product_id` = `Product`.`id`
JOIN `categories` AS `Category` ON `Category`.`id` = `ProductsCategory`.`category_id`
WHERE `Category`.`id` = 3;
SELECT `Product`.*, `Category`.*
FROM `products` AS `Product`
JOIN `products_categories` AS `ProductsCategory` ON `ProductsCategory`.`product_id` = `Product`.`id`
JOIN `categories` AS `Category` ON `Category`.`id` = `ProductsCategory`.`category_id`
WHERE `Category`.`id` = 3
ORDER BY `Product`.`name` ASC
LIMIT 20;
(I.e. select top 20 Products which belong to Category with id = 3)
Note:
Possible solution without Containable would be (as Dave suggested) using joins.
This post offers a very handy helper to build $this->paginate['joins'] to paginate over HABTM association.
Note: Still looking for more elegant solution using Containable than fake hasOne binding.
Finally I found a way to do what I want, so posting it as an answer:
To force JOIN (and be able to filter via condition on associated model) in Containable - you've got to use fake hasOne association.
In my case, code in ProductsController should be:
$this->Product->bindModel(array('hasOne' => array('ProductsCategory')), false);
$this->paginate = array(
'limit' => 20,
'order' => array('Product.name' => 'ASC'),
'conditions' => array(
'ProductsCategory.category_id' => $category
),
'contain' => 'ProductsCategory'
);
$this->set('products', $this->paginate());
Note false as a second argument to bindModel - which makes binding persistent. This is needed because paginate() issues find('count') before find('all'), which would reset temporary binding. So you might want to manually unbindModel afterwards.
Also, if your condition includes multiple IDs in HABTM associated model, you might want to add 'group' => 'Product.id' into your $this->paginate[] (as Aziz has shown in his answer) to eliminate duplicate entries (will work on MySQL only).
UPDATE:
However, this approach has one serious drawback compared to joins approach (suggested by Dave): condition can apply only to intermediate model's foreign key (category_id in my case); if you want to use condition on any other field in associated model - you'd probably have to add another bindModel('hasOne'), binding intermediate model to HABTM associated model.
When you put the condition in the nested Contain, you're asking it to retrieve only the Categories with that ID. So - it's doing what you're asking, but that's not what you want.
Though it seems like it should be possible, the only luck I've had doing what you're trying to do (after MANY hours and a few stackoverflow questions) is via Joins instead of Contain.
http://book.cakephp.org/view/1047/Joining-tables
It's not the exact same problem, but you can go through some of my code where I query against HABTM conditions (I answered my question at the bottom) here: Select All Events with Event->Schedule->Date between start and end dates in CakePHP

Resources