简体   繁体   English

在Cakephp v1.3中运行Model :: find for循环

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

How can I achieve the following result in cakephp: 我如何在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. 我可以使用自定义查询($ this-> Model-> query()函数)轻松地做到这一点,但随后我将面临分页困难。

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. 使用递归属性并将其设置为最大值(2)将降低性能,并且不会产生状态信息。

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). recursive选项设置为3(由于您已经提到的原因,不建议使用)。
  2. Use the Containable behavior. 使用可Containable行为。 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. 不幸的是,我无法Containable行为对分页的影响。

When you use the containable behavior, you don't need to set the recursive level. 当您使用可包含行为时,不需要设置递归级别。 It will be adjusted automatically by cakephp. 它会由cakephp自动调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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