views:

85

answers:

2

Hi all,

How can I achieve the following result in cakephp:

In my application a Topic is related to category, category is related to city and city is finally related to state

in other words:
topic belongs to category, category belongs to city , city belongs to state..

Now in the Topic controller's index action I want to find out all the topics and it's city and state.

How can I do this.

I can easily do this using a custom query ($this->Model->query() function ) but then I will be facing pagination difficulties.

I tried doing like this

function index()
{
    $this->Topic->recursive = 0;
    $topics = $this->paginate();
    for($i=0; $i<count($topics);$i++)
    {
        $topics[$i]['City'] = $this->Topic->Category->City->find('all', array('conditions' => array('City.id' => $topics[$i]['Category']['city_id'])));
    }
    $this->set(compact('topics'));
}

The method that I have adopted is not a good one (running query in a loop)

Using the recursive property and setting it to highest value (2) will degrade performance and is not going to yield me state information.

How shall I solve this ?

Please help

Thanks

+1  A: 

Well, you can do a couple of things:

  1. Set the recursive option to 3 (not recommended for the reasons you've already mentioned).
  2. Use the Containable behavior. The docs I've linked to provide a pretty solid set of usage instructions, I think.

Unfortunately, I can't speak to the impact of the Containable behavior on pagination.

Rob Wilkerson
:-) Thanks. This behavior is awesome, solved my problem.You can set the paginate array in such a way that it will paginate your resultset with no problem, you only need to configure your array properly.
Gaurav Sharma
Good stuff. My own experience with `Containable` has always been a positive one (to say the very least), so I'm glad it worked so well for your issue.
Rob Wilkerson
yeah, earlier (cake v1.2) I wasn't aware of this behavior and I dropped a project because of this functionality. Now when I faced this issue again I decided not to surrender in front of it and stick to cakephp. I am More than happy to learn about this behavior as it answered many of my questions (related to the framework) which I had earlier.
Gaurav Sharma
+1  A: 

When you use the containable behavior, you don't need to set the recursive level. It will be adjusted automatically by cakephp.

user13111984
hmm... true, you're right..
Gaurav Sharma