Developer Blog

  • Blog
  • /
  • ORM relationship preloading
By Dracony on 18 January 2013

ORM has just received a new update. To better explain what is it for consider the following scenario: You have fairies living in trees and you wish to show the name of each fairy and the tree she lives in. You would do it like this:

1
2
3
$fairies=ORM::factory('fairy')->find_all();
foreach($fairies as $fairy)
    echo $fairy->name." ".$fairy->tree->name."<br/>";

The problem with is that for each of these fairies a separate request would be made to the database to get the tree. This is really inefficient, so there is an option to preload them all at once. Like this:

1
2
3
$fairies=ORM::factory('fairy')->with('tree')->find_all();
foreach($fairies as $fairy)
    echo $fairy->name." ".$fairy->tree->name."<br/>";

You can specify multiple relationships to preload and can use the dot notation to preload relationships of those relationships:

1
2
3
4
//This will preload the 'tree' relationship,
//the 'forest' relationship of the tree relationship
//and a 'home' relationship
$fairies=ORM::factory('fairy')->with('tree.forest','home')->find_all();

The only limitation is that only belongs_to and has_one relationships can be preloaded.

1
2
3
//You cannot do this
ORM::factory('tree')->with('fairies')->find_all();
comments powered by Disqus