所以我将我的两个模型连接在一起,它返回的内容如下:
Array
(
[Submission] => Array
(
[id] => 47
[user_id] => 0
[title] => asdfasdfsa dfasdf asdfa sfa fadf
[source] => http://www.aol.com
[slug] =>
[category] => health
[created] => 2012-06-25 11:30:16
)
[User] => Array
(
[id] => 2
[username] => john
)
[SubmissionsVote] => Array
(
[0] => Array
(
[id] => 247
[user_id] => 2
[submission_id] => 47
[vote_type] => up
)
)
)
然而,有时投票数将来自[0] - [n]。这是我的$newestSubmissions
。我正在做的查询是:
public function newestSubmissions() {
$this->unBindModel(
array('hasMany' => array('Comment')));
return $this->find('all', array(
'fields' => array(
'Submission.id',
'Submission.user_id',
'Submission.title',
'Submission.source',
'Submission.slug',
'Submission.category',
'Submission.created',
'User.id',
'User.username'
),
'order' => 'Submission.created DESC'
));
}
我想做的是检索$newestSubmissions
数组对象中的所有投票以及每个$newestSubmissions
上的所有投票(下面的查询)以计算实际得分,以便我可以将一个名为$newestSubmissions
的数组对象发送到我的视图,而不是$newestSubmissions
和$submissionScore
public function getVoteType($userId, $submissionId) {
$voteType = $this->find('all', array(
'conditions' => array(
'User.id' => $userId,
'Submission.id' => $submissionId),
'fields' => array(
'SubmissionsVote.vote_type'),
'limit' => '1'
));
return $voteType[0]['SubmissionsVote']['vote_type'];
}
基本上我想在我的视图中发送一个分数以及数组对象中的所有其他信息,而不是必须在我的父数组对象中发送内部索引数组对象(这是我目前得到的)。
我该怎么做?
答案 0 :(得分:0)
好的......我试图将此作为评论发布,但时间太长了。这不是一个真正的答案。
你知道可容纳的行为吗?检查出来 - 这有助于确定您获得的数据:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
另外,如果您将提交投票表分为两个表 - upvotes和downvotes,那么您还可以使用Cake的counterCache行为直接在“提交”表中跟踪上/下投票的数量(您我需要将upvote_count和downvote_count列添加到您的提交表中以执行此操作。)
这将使计算提交分数更容易 - 并且您不必每次都从数据库中获取所有投票。对于doco,请在此页面上搜索counterCache:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html值得考虑。
答案 1 :(得分:0)
return $this->find('all', array(
'fields' => array(
'Submission.id',
'Submission.user_id',
'Submission.title',
'Submission.source',
'Submission.slug',
'Submission.category',
'Submission.created',
'User.id',
'User.username',
'submissionsvotes.vote_type'
),
'joins' => array(
array(
'table' => 'SubmissionsVote',
'alias' => 'submissionsvotes',
'type' => 'LEFT',
'conditions' => array
('User.id = SubmissionsVotes.user_id','Submission.id'=>'SubmissionsVotes.submission_id')
),
)
'group'=>'submissionsvotes.vote_type',
'order' => 'Submission.created DESC'
)
);