如何在cakephp中找到关联表的最后一条记录?

如何在cakephp中找到关联表的最后一条记录?,php,cakephp,model,cakephp-2.0,Php,Cakephp,Model,Cakephp 2.0,我使用的是CakePHP2.4.5。我想找到关联表的最后一条记录。下面是我的代码 $Latest = $this->ParentModel->find('first',array( 'conditions' => array('ParentModel.id'=>$id), 'order' => array('ParentModel.Associated

我使用的是CakePHP2.4.5。我想找到关联表的最后一条记录。下面是我的代码

    $Latest = $this->ParentModel->find('first',array(
                           'conditions' => array('ParentModel.id'=>$id),
                           'order' => array('ParentModel.AssociatedModel.id' => 'DESC')
                                                          ));    
此代码缺少ParentModel.AssociatedModel.id的列错误,但id列肯定在那里。一开始看起来对吗?如果没有,我如何修复此部分,或者是否有更好的实现?谢谢

您不能通过关联模型执行“交叉条件”,但您可以使用
可包含的
行为来过滤关联模型

为此,必须通过以下方式将行为绑定到模型:

public $uses = array('Containable');
然后执行查询:

$this->ParentModel->find('first', array(
    'conditions' => array('ParentModel.id' => $id),
    'contain' => array(
        'AssociatedModel' => array(
            'limit' => 1,
            'order' => array('id DESC')
        )
    )
));

这将为您提供父模型和最后一个关联模型。

我想应该是这样的

    $Latest = $this->ParentModel->AssociatedModel->find('first',array(
                       'conditions' => array('ParentModel.id'=>$id),
                       'order' => array('AssociatedModel.id DESC')
                                                      ));    
检查它是否正确。

?这里有清楚的解释

如果关联模型以某种方式与ParentModel关联,则必须使用以下语法:

$Latest = $this->ParentModel->find('first',array(
   'contain' => array('AssociatedModel'),
   'conditions' => array('ParentModel.id' => $id),
   'order' => array('AssociatedModel.id' => 'DESC')
)); 
确保使用递归或contain()包含另一个模型

如果数据库中的字段名确实包含一个点CakePHP2,则会出现问题,因为它使用点符号作为分隔符。至少我从来没有在数据库字段中使用过点,这是可行的,但没有多大意义,显然会弄坏蛋糕,不知道您是否可以解决这个问题