【问题标题】:cakephp find associated models of associated modelcakephp 查找关联模型的关联模型
【发布时间】:2014-07-21 20:47:23
【问题描述】:

我正在调用与模型 Page(book_id) 关联的名为 Book 的模型上的查找

但是,Page 与名为 Asset(page_id) 的模型相关联。我想得到所有三个模型的数组

Book
    Page1
        Asset1
        Asset2
        Asset3
    Page2
        Asset1
        Asset2
        Asset3

我目前拥有的代码只能得到我的书和页面

$options = array(
    'conditions' => array('Book.' . $this->Book->primaryKey => $id),
    'contain' => 'Page'
);
$books = $this->Book->find('first', $options);

书有很多页 页面有很多资产

【问题讨论】:

    标签: cakephp cakephp-2.5


    【解决方案1】:

    您可以包含更深层次的关联,就像 docs 中所说的那样

    文档中的示例

    $this->User->find('all', array(
        'contain' => array(
            'Profile',
            'Account' => array(
                'AccountSummary'
            ),
            'Post' => array(
                'PostAttachment' => array(
                    'fields' => array('id', 'name'),
                    'PostAttachmentHistory' => array(
                        'HistoryNotes' => array(
                            'fields' => array('id', 'note')
                        )
                    )
                ),
                'Tag' => array(
                    'conditions' => array('Tag.name LIKE' => '%happy%')
                )
            )
        )
    ));
    

    你的模型也一样...

    $options = array(
        'conditions' => array('Book.' . $this->Book->primaryKey => $id),
        'contain' => array('Page' => array('Asset')))
    );
    $books = $this->Book->find('first', $options);
    

    如果您的关联设置正确(并且如果所有模型都实现了可包含的行为),则应该可以工作。

    编辑
    (以解决 OP 的困惑)

    嵌套包含选项适用于扩展数组的模型。例如,如果模型是这样关联的

    Model-A -> Model-B -> Model-C & Model-D
            -> Model-E -> Model-C
    

    你可以得到整个数组的数据,比如

    Model-A
      Model-B1
        Model-C1
        Model-C2
        Model-D2
      Model-B2
        Model-C (null)
        Model-D3
      Model-E1
        Model-C1
        Model-C3
    

    使用类似的东西

    $this->ModelA->find('all'), array(
           'contain' => array(
              'Model-B' => array('Model-C', 'Model-D'),
              'Model-E' => array('Model-C')
           )
    );
    

    另外,你可以add options 到可包含数组,包括用于搜索的数组,比如'conditions'(虽然要小心,这意味着如果模型不匹配条件,它将返回 null数组,它确实意味着整个“Model-A”将不在返回的数据中,因为其中一个嵌套条件没有满足)。

    【讨论】:

    • 谢谢,我在阅读文档时误解了它。我认为资产必须与 Book 相关联才能正常工作。结果现在很完美。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多