【问题标题】:CakePHP Containable behaviour not working as expectedCakePHP 包含的行为未按预期工作
【发布时间】:2012-10-24 19:00:31
【问题描述】:

我正在尝试从 2 层深的模型中检索特定字段。 我正在使用容器行为,但未正确检索底层。

代码如下:

$this->Review->Behaviors->attach('Containable');
    $latestReviews = $this->Review->find('all', array(
        'contain' => array(
            'Business' => array(
                'fields' => array('Business.name'),
                'BusinessType' => array(
                    'fields' => array('BusinessType.url')
                )
            ),
        ),
        'fields' => array('overall'),
    ));

以及它返回的数组:

array(
(int) 0 => array(
    'Review' => array(
        'overall' => '2'
    ),
    'Business' => array(
        'name' => 'Business Name',
        'business_type_id' => '1',
        'id' => '2012'
    )
))

但是,我希望它返回 BusinessType url 字段,而不是给我业务类型 ID。

谁能看到我哪里出错了?我确定这与 CakePHP 文档是一致的。

【问题讨论】:

  • 我认为您的 BusinessType 嵌套不正确 - 将其提升一级。 contain('Business' => array(...), 'BusinessType' => array(...))

标签: php cakephp containable


【解决方案1】:

引用手册:

使用“字段”和“包含”选项时 - 小心包含您的查询直接或间接需要的所有外键。

【讨论】:

  • 谢谢,错过了那一点。将 business_id 添加到顶级字段数组中,瞧
  • 另外,现在使用 3.x,您可以在关联上调用 select(),在下面查看我的答案。
【解决方案2】:

我认为您应该删除字段列表中的“字段”选项和模型名称:

$this->Review->Behaviors->attach('Containable');
$latestReviews = $this->Review->find('all', array(
    'contain' => array(
        'Business' => array(
            'fields'       => array('name'),
            'BusinessType' => array(
                'fields' => array('url')
            )
        )
    )));

【讨论】:

    【解决方案3】:

    使用 3.x 版本:

    如果您使用 select() 限制了要加载的字段,但也 想要从包含的关联中加载字段,您可以通过 select() 的关联对象:

    // Select id & title from articles, but all fields off of Users.
    $query = $articles->find()
        ->select(['id', 'title'])
        ->select($articles->Users)
        ->contain(['Users']);
    

    $articles 等同于问题中的$this->Review

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 2013-06-04
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多