【发布时间】:2017-05-20 22:24:33
【问题描述】:
我正在尝试将 SQL 查询转换为 CakePHP 查询。 SQL 查询返回一行,CakePHP 查询返回 2 行,第一行是 id & cover 列,第二行是 files_with_cover . 当然,我想要一行包含所有列。
SQL 查询:
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 查询:
$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)
));
编辑,示例数据集:
id cover source_path
-----------------------
1 image1 /example/1
2 image1 /example/2
3 image1 /example/3
4 image2 /example/4
使用条件 source_path "/example/1" 进行选择时,我想要以下结果: id = 1,cover = image1,files_with_cover = 3。
$result 数组的打印输出可能会提供线索。不知道为什么 files_with_cover 列在单独的行中结束。
Array
(
[Song] => Array
(
[id] => 1
[cover] => cover1.jpeg
)
[0] => Array
(
[files_with_cover] => 3
)
)
使用 CakePHP 2.8.1 和 MySQL
【问题讨论】:
-
去掉
files_with_cover周围的引号,然后再检查一次,如果不起作用,请显示CakePHP生成的查询(检查DebugKit)。 -
我不太明白这个查询。我认为数据集和期望的结果可能更具启发性
-
files_with_cover 周围的引号不应该也不会产生影响,但无论如何都将其删除。添加了示例数据集和所需结果以进行澄清。检查 MySQL 和执行的实际查询看起来没问题。还打印了可能提供线索的 $result 数组。使用信息更新的原始帖子。
-
按歌曲 ID 分组
标签: php mysql sql cakephp left-join