How do I efficiently load multiple has_many relati

2019-08-09 00:38发布

问题:

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!