Question

Just wondering if there is an easy way to auto-populate an object’s related fields on an instance-by-instance basis rather than globally in the config file, or, for the entire class.

I’d like to include all related models for a single instance without chaining a ton of include_related() functions. Something like this would be nice:

$x = new Model();
$x->include_all_related();
Was it helpful?

Solution

Thought I'd have to get my hands dirty in the core. For whatever reason, it didn't occur to me that I could access the $has_many and $has_one arrays.

Solution was simple:

class Model extends Datamapper{
    var $has_one = array('foo', 'bar', 'baz');
    var $table = 'models';

    function __construct($id = NULL){
        parent::__construct($id);
    }

    function include_all_related(){
        foreach($this->has_one as $h){
            $this->include_related($h['class']);
        }
        return $this;
    }
}

You might wonder why I'm using the class key in the $h variable. Under the hood, Datamapper ORM keeps track of some other keys too as part of a bigger array. If you call print_r($h), you can see them. The class key keeps track of foo, bar and baz.

OTHER TIPS

You can enable it on the relation definition, if you want is on a particular instance, you need to change the relation configuration of that instance at runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top