任何人都可以告诉我,如何从cakePHP中的多个表中检索连接结果(使用cakePHP mvc架构).例如,我有三个表要加入(tbl_topics,tbl_items,tbl_votes.他们的关系定义如下:一个主题可以有很多项目,一个项目可以有很多选票.现在我想检索一个主题列表,其中包括每个主题的所有项目的所有投票.对此的SQL查询如下:
SELECT Topic.*, count(Vote.id) voteCount
FROM
tbl_topics AS Topic
LEFT OUTER JOIN tbl_items AS Item
ON (Topic.id = Item.topic_id)
LEFT OUTER JOIN tbl_votes AS Vote
ON (Item.id = Vote.item_id);
Run Code Online (Sandbox Code Playgroud)
我的问题是我可以使用$this-><Model Name>->query函数轻松完成,但这需要在我不想要的控制器中编写sql代码.我试图找出任何其他方法来做到这一点(比如find()).
小智 41
$markers = $this->Marker->find('all', array('joins' => array(
array(
'table' => 'markers_tags',
'alias' => 'MarkersTag',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array('MarkersTag.marker_id = Marker.id')
),
array(
'table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array(
'Tag.id = MarkersTag.tag_id',
'Tag.tag' => explode(' ', $this->params['url']['q'])
)
)
)));
Run Code Online (Sandbox Code Playgroud)
正如nate abele的文章中提到的:链接文本
我在这里诚实地说,如果您只是在模型中创建一个函数,例如 getTopicVotes() 并在那里调用 query() ,您可能会更高兴。我能想到的所有其他解决方案只会让它变得更复杂,因此更丑陋。
编辑:
根据数据的大小,并假设您已正确设置模型关系(主题 hasMany Items hasMany Votes),您可以执行一个简单的 find('all') 包含所有项目和投票,然后执行类似的操作这:
foreach ($this->data as &$topic)
{
$votes = Set::extract('/Topic/Item/Vote', $topic);
$topic['Topic']['vote_count'] = count($votes);
}
Run Code Online (Sandbox Code Playgroud)
这里有两件事很重要: