How do I efficiently load multiple has_many relationships in CodeIgniter DataMapper ORM?

左心房为你撑大大i 提交于 2019-12-13 02:08:37

问题


Given the following models:

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();
  }
}

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


回答1:


You can use the following

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
            }
        }
    }

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;

Hope it helps!



来源:https://stackoverflow.com/questions/15122537/how-do-i-efficiently-load-multiple-has-many-relationships-in-codeigniter-datamap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!