如何在CakePHP中的多个表中编写连接查询?

Man*_*rma 15 cakephp join

任何人都可以告诉我,如何从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的文章中提到的:链接文本

  • 上面的find函数只获取Marker表中的字段而不是其他两个表. (3认同)
  • @NaveenKumar:你必须提到另一个数组中的字段,例如$ this-> Marker-> find('all',array('joins'=> array(.....),'fields'=> array(MarkersTag. marker_id,Marker.id)); (3认同)

dr *_*ter 2

我在这里诚实地说,如果您只是在模型中创建一个函数,例如 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)

这里有两件事很重要:

  1. 如果您有大量数据,您可能应该忘记这种方法,它会非常慢。
  2. 我是凭记忆写下这篇文章的,在现实生活中它可能看起来不像这样和/或它可能根本不起作用:-)