【问题标题】:How to find the last record of an associated table in cakephp?如何在cakephp中找到关联表的最后一条记录?
【发布时间】:2014-03-20 11:51:48
【问题描述】:

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

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

此代码有 ParentModel.AssociatedModel.id 的缺失列错误,但 id 列肯定存在。它首先看起来正确吗?如果没有,我该如何修复这部分或有更好的实现?谢谢

【问题讨论】:

    标签: php cakephp model cakephp-2.0


    【解决方案1】:

    Have you tried to read the manual about retrieving data?那里解释的很清楚。

    如果 AssociatedModel 以某种方式将with one of the four association types 与ParentModel 相关联,则必须使用以下语法:

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

    使用递归或contain() 确保包含另一个模型。 See this page about Containable.

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

    【讨论】:

      【解决方案2】:

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

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

      public $uses = array('Containable');
      

      然后进行查询:

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

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

      【讨论】:

        【解决方案3】:

        我猜应该是这样的

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

        检查是否正确。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-23
          相关资源
          最近更新 更多