可容纳和深度关联的数据 [英] Containable and deep associated data

查看:193
本文介绍了可容纳和深度关联的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

document has many document_item
document_item has many document_item_description and belongs to document
document_item_description has one document_item

我正在尝试获取一个包含所有document_item的文档和所有相关联的document_items的相关document_item_descriptions

I'm trying to get a document with all document_items and all associated document_item_descriptions for the associated document_items

有办法做到这一点吗?

Is there a way to do this? Right now all I can get are document_items but can't get down to the third level.

        class Document extends AppModel {
        public $hasMany = array(
            'Document_item' => array(
                'className' => 'document_item',
                'foreignKey' => 'document_id'
                )
            );



    class DocumentItem extends AppModel {
        public $belongsTo = array(
            'document' => array(
                'className' => 'document',
                'foreignKey' => 'document_id'
                ));

        public $hasMany = array(
            'document_item_description' => array(
                'className' => 'document_item_description',
                'foreignKey' => 'document_item_id'
                ));
    }

    class DocumentItemDescription extends AppModel {
        public $hasOne = array(
            'document_item' => array(
                'className' => 'document_item',
                'foreignKey' => 'document_item_id'

                ));
    }

在我的控制器中,我使用的是:

In my controller I'm using:

 public function index(){
    $res = $this->Document->find('all', array('recursive' => 3));
}


推荐答案

你自己的问题。您应该使用可控行为,而不是 recursive 选项。 递归选项已从新的CakePHP 3中删除,因为它在开销上很重,我建议您尽量避免使用它。为了得到你的深数据,首先将它添加到您的模型文件(或更好的,你的AppModel,所以你可以随时使用它):

Your question title pretty much answers your own question. You should use Containable behavior and not the recursive option. The recursive options has been removed from the new CakePHP 3, because it's very heavy on overhead and I would recommend you to avoid using it as much as you can. In order to get your 'deep' data, first add this to your Model files (or better yet, your AppModel, so you can always use it):

public $actsAs = array('Containable');

这将启用模型的可控行为。然后,您可以使用包含键在查找中将表连接到一起,如下所示:

That will enable the containable behavior for your models. Then you can use the contain key in your find to join tables together, like this:

$this->Document->find('all', array(
    'contain' => array(
        'DocumentItem' => array(
            'DocumentItemDescription'
        )
    )
));

这将给你一个包含相关数据的数据数组。您还可以通过在任何数组中指定 fields 选项来筛选您希望每个模型的哪些字段。

That will give you a data array with the related data as well. You can also filter which fields you want per Model by specifying a fields option inside any of the arrays.

这篇关于可容纳和深度关联的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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