문제

I am using cakephp 2.4.5. I want to find the last record of an associated table. Below is my code

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

This code has missing column error with ParentModel.AssociatedModel.id but the id column is definitely there. Does it look right in the first place? If not, how can I fix this part or is there a better implementation? Thank you

도움이 되었습니까?

해결책

Have you tried to read the manual about retrieving data? It is clearly explained there.

If AssociatedModel is somehow associated with one of the four association types with ParentModel, you'll have to use this syntax:

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

Make sure the other model is included by using recursive or contain(). See this page about Containable.

If your field name in the DB is really containing a dot CakePHP2 will have a problem with that because it uses the dot notation as separator. At least I've never used a dot in a database field, it's doable but doesn't make much sense and obviously breaks Cake, no idea if you can work around that.

다른 팁

You can't do "cross conditions" though associated models, but you can use Containable behavior to filter associated models.

For this, you have to bind the behavior to your model through:

public $uses = array('Containable');

And then do your query:

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

This will give you the parent model, and the last associated model.

I guess it should be like this

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

Check if it is correct.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top