1
votes

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();
2
I don't think DataMapper has any built-in function for that. You could just add the include_all_related() function to the model to simply save having to write the code over and over? - froddd
Thanks @froddd - Yeah, that's the approach I'm taking now - but it means when I create a new model and fill out it's relationships ($has_many() and $has_one()), I also have to head into the include_all_related() function and make adjustments there too. I've asked it on DMORM CI Forum too. Our solution is a temporary fix, when I'm less busy, and provided I don't get an answer, I'll dig into the core and create a method myself :D - Jordan Arseno
Actually, I don't have to keep changing the include_all_related() function if I just read in the $has_one or $has_many arrays. facepalm. See solution below. - Jordan Arseno

2 Answers

1
votes

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.

0
votes

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.