如何有效地在CodeIgniter DataMapper ORM中加载多个has_many关系? [英] How do I efficiently load multiple has_many relationships in CodeIgniter DataMapper ORM?

查看:73
本文介绍了如何有效地在CodeIgniter DataMapper ORM中加载多个has_many关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下模型:

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

Category: has_many(‘template’) Template: has_many(‘tag’, ‘procedure’)

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

What is the most efficient way to load ALL objects related to ALL categories?

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

For instance, I’m currently doing the following, but hopefully there is a better way:

// 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多个查询

Right now this code is executing over 200 queries on one particular page.

推荐答案

您可以使用以下

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 application / config / datamapper.php中的autopopulate选项,并且不需要在所有模型上运行get()

Make sure you have activated the autopopulate option in the datamapper config application/config/datamapper.php and you dont need to run get() on all models

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

希望有帮助!

这篇关于如何有效地在CodeIgniter DataMapper ORM中加载多个has_many关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆