gpt4 book ai didi

php - CakePHP 查询返回两行而不是一行

转载 作者:行者123 更新时间:2023-11-29 18:56:40 25 4
gpt4 key购买 nike

我正在尝试将 SQL 查询转换为 CakePHP 查询。 SQL 查询返回一行,而 CakePHP 查询返回 2 行,第一行包含 idcover 列,第二行包含 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,封面 = 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

最佳答案

您收到的不是两行(数据库),只是一个未完全分组的单行。如果您希望所有内容都分组在主模型别名下,则需要使用虚拟字段。

$this->Song->virtualFields['files_with_cover'] = 'count(Song2.id)';
'fields' => array('Song.id', 'Song.cover', 'files_with_cover'),

另请参阅 Cookbook > Models > Virtual Fields

关于php - CakePHP 查询返回两行而不是一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44091369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com