我正在使用Cake
PHP进行CMS / Web服务来为iPhone应用程序供电.我想知道如何订购我的.find()方法,以便我可以通过一些外部模型的“计数”来订购?
例如:
视频对象与投票相关联.因此,单个视频行有多个投票行(带有user_id和video_id).
$videos = $this->Video->find('list', array( <<orderby stuff>> ));
如何更改orderby子句,以便通过投票返回25个最受欢迎的视频?
最佳答案 我们假设您有以下表格:
CREATE TABLE `videos` (
`id` char(36) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `votes` (
`id` char(36) NOT NULL,
`video_id` char(36) NOT NULL,
`user_id` char(36) NOT NULL,
PRIMARY KEY (`id`)
);
您尝试编写的SQL类似于:
SELECT
count(id),
video_id
FROM votes
GROUP BY video_id
ORDER BY count(id) DESC
LIMIT 25;
问题是,它不会返回视频名称.这可以通过JOIN或使用蛋糕递归功能轻松解决.鉴于以上情况,我会写以下内容:
$this->Vote->recursive = 1;
$vote_info = $this->Vote->find('all',
array(
'fields' => array('count(Vote.id)','Video.name'),
'group' => array('video_id'),
'order' => array('count(Vote.id) DESC'),
'limit' => 25,
)
);
当您获得数据时,只要模型中的关系设置正确,您还将获得视频信息(由于递归选项设置为1).
例如,数据看起来像:
Array
(
[0] => Array
(
[0] => Array
(
[count(`Vote`.`id`)] => 3
)
[Video] => Array
(
[name] => Dumb and Dumber
)
)
[1] => Array
(
[0] => Array
(
[count(`Vote`.`id`)] => 1
)
[Video] => Array
(
[name] => Lord of the Rings
)
)
[2] => Array
(
[0] => Array
(
[count(`Vote`.`id`)] => 1
)
[Video] => Array
(
[name] => Just Do It
)
)
)
我想您可以从这里看到如何访问视图中的数据.
Hoppy编码!
更新:
如果您只需要视频ID,则可以执行以下操作:
$this->Vote->recursive = 0;
$votes = $this->Vote->find('all',
array(
'fields' => array('count(Vote.id) as count', 'Vote.video_id'),
'order' => array('count(Vote.id) DESC'),
'group' => array('Vote.video_id'),
'limit' => 25,
)
);
这将返回:
Array
(
[0] => Array
(
[0] => Array
(
[count] => 3
)
[Vote] => Array
(
[video_id] => 4dac4de7-4f80-48c1-8a02-83b4dfa458e5
)
)
[1] => Array
(
[0] => Array
(
[count] => 1
)
[Vote] => Array
(
[video_id] => 4dac4ddc-712c-4795-8d9a-83b4dfa458e5
)
)
[2] => Array
(
[0] => Array
(
[count] => 1
)
[Vote] => Array
(
[video_id] => 4dac4df0-382c-4bb5-a5ee-83b4dfa458e5
)
)
)