Home » Php » php – On Silverstripe, how do I retrieve a DataList of grandchild objects including their extrafields?

php – On Silverstripe, how do I retrieve a DataList of grandchild objects including their extrafields?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a setup similar to that outlined below.

class A extends DataObject{
    private static $many_many = array(
        'Bs' => 'B'
    );

    public function Grandchildren(){
        // return grandchildren, including their many_many_extraFields data (ExtraData)
    }
}

class B extends DataObject{
    private static $many_many = array(
        'Cs' => 'C'
    );

    private static $belongs_many_many = array(
        'As' => 'A'
    );

    private static $many_many_extraFields = array(
        'As' => array(
            'ExtraData' => 'Int'
        )
    );
}

class C extends DataObject{
    private static $db = array(
        'Name' => Varchar(255)
    );

    private static $belongs_many_many = array(
        'Bs' => 'B'
    );
}

I wish to retrieve all the C objects of all the B objects from a function on A (here called Grandchildren()).

Two potential solutions that I can’t get to work:

1 –

public function Grandchildren(){
    $grandchildren = DataList::create();
    foreach($this->Bs() as $b){
        $Cs = $b->Cs();
        // How would I then merge these into one single DataList ($grandchildren)?
    }
    return $grandchildren;
}

2 –

public function Grandchildren(){
    return C::get()->leftJoin('B_Cs', 'B_Cs.CID = C.ID')->where('B_Cs.AID = ' . $this->ID);
    // This works but doesn't contain the needed ExtraData.
}

Many thanks in advance for any help.

How to&Answers:

Ah sorry. The answer was much simpler than I realised. Just took going through every method on the docs for DataList again.

public function Grandchildren(){
    return $this->Bs()->relation('Cs');
}

Leaving question and answer here to help any of those stuck in the same situation as me (as I’ve been stuck with this problem many times before).