CakePHP 3 Fetch associated data recursive

孤街醉人 提交于 2019-12-11 11:55:35

问题


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!


回答1:


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();


来源:https://stackoverflow.com/questions/33396461/cakephp-3-fetch-associated-data-recursive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!