简体   繁体   中英

Running a Model::find in for loop in cakephp v1.3

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM