代码之家  ›  专栏  ›  技术社区  ›  Keith Power

cakephp查找关联模型的关联模型

  •  1
  • Keith Power  · 技术社区  · 10 年前

    我正在调用一个名为Book的模型上的查找,该模型与模型Page(Book_id)关联

    然而,Page与一个名为Asset(Page_id)的模型相关联。我想得到所有三种型号的阵列

    Book
        Page1
            Asset1
            Asset2
            Asset3
        Page2
            Asset1
            Asset2
            Asset3
    

    我现在的代码只给我Book和Page

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

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

    1 回复  |  直到 10 年前
        1
  •  3
  •   Nunser    10 年前

    你可以包含更深层次的关联,就像它在 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' (尽管要小心,这意味着如果模型与条件不匹配,它将返回一个空数组 意味着整个“Model-A”将不在返回的数据中,因为其中一个嵌套条件未满足)。