I'm trying to translate an SQL query into a CakePHP query. Where the SQL query returns one row, the CakePHP query returns 2 rows with the columns id & cover in the first row & files_with_cover in the second. Naturally I'd like one row with all columns.
SQL query:
SELECT s1.id, s1.cover, COUNT(s2.id) files_with_cover FROM songs s1 LEFT JOIN songs s2 ON s2.cover=s1.cover WHERE s1.source_path=$path
CakePHP query:
$result = $this->Song->find('first', array(
'joins' => array(
array(
'table' => 'songs',
'alias' => 'Song2',
'type' => 'LEFT',
'conditions' => array('Song2.cover = Song.cover')
)
),
'fields' => array('Song.id', 'Song.cover', 'count(Song2.id) as files_with_cover'),
'conditions' => array('Song.source_path' => $file)
));
EDIT, example data set:
id cover source_path
-----------------------
1 image1 /example/1
2 image1 /example/2
3 image1 /example/3
4 image2 /example/4
When doing a select with the conditional source_path "/example/1" I want the following result: id = 1, cover = image1, files_with_cover = 3.
The printout from the $result array may give a clue. Not sure why the files_with_cover column ends up in a separate row.
Array
(
[Song] => Array
(
[id] => 1
[cover] => cover1.jpeg
)
[0] => Array
(
[files_with_cover] => 3
)
)
Using CakePHP 2.8.1 & MySQL
What you receive there isn't two (database) rows, just a not entirely grouped single row. You need to use virtual fields if you want everything grouped under the main model alias.
$this->Song->virtualFields['files_with_cover'] = 'count(Song2.id)';
'fields' => array('Song.id', 'Song.cover', 'files_with_cover'),
See also Cookbook > Models > Virtual Fields
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.