如何在CodeIgniter DataMapper ORM中高效加载多个has_many关系?

时间:2013-02-27 21:14:10

标签: codeigniter codeigniter-2 codeigniter-datamapper

鉴于以下模型:

类别:has_many('模板') 模板:has_many('tag','procedure')

加载与所有类别相关的所有对象的最有效方法是什么?

例如,我目前正在做以下事情,但希望有更好的方法:

// Load all Category objects
$categories = new Category();
$categories->get();

// Load all Template objects related to each Category
foreach($categories as $category)
{
  $category->templates->get();

  // Load all the Tag and Procedure objects related to each template
  foreach($category->templates as $template)
  {
    $template->tags->get();
    $template->procedures->get();
  }
}

现在,此代码在一个特定页面上执行了200多个查询。

1 个答案:

答案 0 :(得分:0)

您可以使用以下

foreach($categories as $category)
    {
        // here you can use the $category object
        foreach($category->templates as $template){
            // here you can use the $template object
            foreach($template->tags as $tags){
                // here you can use the $tags object
            }
            foreach($template->procedures as $proceadures){
                // here you can use the $proceadures object
            }
        }
    }

确保您已在datamapper配置应用程序/ config / datamapper.php中激活了autopopulate选项,并且您不需要在所有模型上运行get()

$config['auto_populate_has_many'] = TRUE;
$config['auto_populate_has_one'] = TRUE;

希望它有所帮助!