How do I write a join query across multiple tables in CakePHP?

后端 未结 6 1682
既然无缘
既然无缘 2020-11-28 07:50

can anyone tell me, how to retrieve joined result from multiple tables in cakePHP ( using cakePHP mvc architecture). For example, I have three tables to join (tbl_topics, tb

6条回答
  •  暖寄归人
    2020-11-28 08:16

    I'll be honest here and say that you'll probably be a lot happier if you just create a function in your model, something like getTopicVotes() and calling query() there. Every other solution I can think of will only make it more complicated and therefore uglier.

    Edit:

    Depending on the size of your data, and assuming you've set up your model relations properly (Topic hasMany Items hasMany Votes), you could do a simple find('all') containing all the items and votes, and then do something like this:

    foreach ($this->data as &$topic)
    {
        $votes = Set::extract('/Topic/Item/Vote', $topic);
        $topic['Topic']['vote_count'] = count($votes);
    }
    

    Two things are important here:

    1. If you have a lot of data, you should probably forget about this approach, it will be slow as hell.
    2. I've written this from my memory and it might not look like this in real life and/or it may not work at all :-)

提交回复
热议问题