PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

[FIXED] CakePHP 3 Fetch associated data recursive

 February 22, 2022     cakephp, cakephp-3.0, php, recursion     No comments   

Issue

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!


Solution

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


Answered By - floriank
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing