1

I am trying to fetch Data in a recursive-way (over associations) using CakePHP 3.1

In Cake 3 I can use the "contain" key to fetch the next level of asociated data. But I need to fetch one more level. Does anyone know how to do this? I read the docs but didn't found anything there, with google it's the same.

The 3 Levels are connected like this: OperationalCostInvoice (belongsTo Object) -> Object (hasMany OperationalCostTypes) -> OperationalCostType

With OperationalCostInvoice->get($object_id, ['contain' => 'Object']) I can get the Object that is associated with the OperationalCostInvoice but I also want to fetch the OperationalCostTypes from the Object in (if possible) just one call.

I dont need tipps about association linking the reason that the entities are linked like this is I can easily implement a history function.

Thanks in advance!

  • As you've got a `hasMany` relationship Cake won't be able to do this in one query, it will have to fetch the `OperationalCostTypes` independently. – drmonkeyninja Oct 28 '15 at 17:00
  • Thanks for your comment! I just meant one function call (on the Table object) to fetch everything. I know that more than one query is required. But in CakePHP 2 there was the option recursive which controlled on how many levels associated data is fetched. – Kevin Neumeyer Oct 28 '15 at 17:02

1 Answers1

5

I just meant one function call (on the Table object) to fetch everything. I know that more than one query is required.

Just create your own table method then and return all your results in one array or implement whatever you want and return it.

public function foo() {
    return [
        'one' => $this->find()...->all();
        'two' => $this->Asssoc->find()...->all();
    ];
}

But in CakePHP 2 there was the option recursive which controlled on how many levels associated data is fetched.

The recursive was a pretty stupid thing in Cake2. First thing we've always done was to set it to -1 in the AppModel to avoid unnecessary data fetching. Using contain is always the better choice. I would stay away from using recursive at all, especially for deeper levels.

Also contain is still, as it was in Cake2 as well, able to fetch more than one level deep associations.

$this->find()->contain([
    'FirstLevel' => [
        'SecondLevel' => [
            'ThirdLevel'
        ]
    ]
])->all();
floriank
  • 25,546
  • 9
  • 42
  • 66
  • Thanks it works. I also set recursive to -1 in most cases, just want to show that in Cake 2 there was a solution like that. Didn't knew that one can nest contain conditions like this, works like a charm :) – Kevin Neumeyer Oct 28 '15 at 17:22
  • You're not still setting `recursive = -1` in Cake 3, are you? It's not a feature any more, so that would be wasted and confusing code. – Greg Schmidt Oct 30 '15 at 16:08