0

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

3 Answers 3

1

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.

1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.