Cakephp:包含限制1,不显示任何关联项目,其中有多个项目

时间:2015-04-28 21:10:36

标签: cakephp limit contain

我有2个型号: Surveyaccess和Datapoint

他们有HABTM关系。

如果我想列出每个调查访问和相关的数据点,我可以这样做:

$t = $this->Surveyaccess->find('all', array(
    'contain' => array(
        'Datapoint'
    ),
    'conditions' => $conds,
));
//$conds are limiting me to a specific set of Surveyaccess items - not relevant here

但我真正想要的只是显示每个Datapoint项目的第一个(如果有的话)

我试过了:

$t = $this->Surveyaccess->find('all', array(
    'contain' => array(
        'Datapoint' => array(
            'limit' => 1
        )
    ),
    'conditions' => $conds,
));

我希望LIMIT可以将返回的项限制为1 - 但是当有超过1个Datapoint项时,它只是返回一个空数组:

(int) 0 => array(
        'Surveyaccess' => array(
            'id' => '63617',
            'browser' => 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36',
            'created' => '2015-02-28 01:55:28',
            'read' => null
        ),
        'Datapoint' => array()
    ),
...
(int) 2 => array(
        'Surveyaccess' => array(
            'id' => '63615',
            'browser' => 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36',
            'created' => '2015-02-28 01:42:58',
            'read' => null
        ),
        'Datapoint' => array(
            (int) 0 => array(
                'id' => '258',
                'DatapointSurveyaccess' => array(
                    'id' => '258',
                    'surveyaccess_id' => '63615',
                    'datapoint_id' => '258'
                )
            )
        )
    ),

有关如何正确执行此操作的任何想法?我可以用PHP处理数组,但不能扩展。我也可以做一个子查询...

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

我认为你需要找到('第一个')

$t = $this->Surveyaccess->find('first', array(
    'contain' => array(
        'Datapoint'
    ),
    'conditions' => $conds,
));

<强>已更新

$t = $this->Surveyaccess->find('all', array(
    'limit' => 1,
    'contain' => array( 
        'Datapoint' 
    ) 
));