CakePHP 3提取关联数据递归 [英] CakePHP 3 Fetch associated data recursive

查看:67
本文介绍了CakePHP 3提取关联数据递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CakePHP 3.1以递归方式(通过关联)获取数据

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

在Cake 3中,我可以使用包含键来获取下一级别的关联数据。但是我需要再获取一个级别。有谁知道如何做到这一点?我看过文档,但没有找到任何文档,与Google相同。

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.

三个级别的连接方式如下:
OperationalCostInvoice(属于对象)
->对象(hasMany OperationalCostTypes)
-> OperationalCostType

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

带有 OperationalCostInvoice-> get($ object_id,['contain'=>'Object'] )我可以获取与OperationalCostInvoice关联的对象,但我也想通过一次调用(如果可能)从该对象中获取OperationalCostTypes。

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.

谢谢!

推荐答案


我的意思是一个函数调用(在Table对象上)获取一切。我知道需要多个查询。

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




但是在CakePHP 2中有递归选项哪个控制了关联数据的获取级别。

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

在Cake2中,递归是一件很愚蠢的事情。我们一直要做的第一件事是在AppModel中将其设置为 -1 以避免不必要的数据获取。始终使用包含是 更好的选择。我根本不会使用递归,尤其是更深层次的

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.

就像在Cake2中一样,contain仍然能够获取多个级别的深层关联。

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

这篇关于CakePHP 3提取关联数据递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆