简体   繁体   中英

CakePHP find with “contain”

My model has many relationships to other tables/models, if i use contain parameter, for example to order by field in results of one model, all other tables in query results are missing, and must manually written in contain parameter, how can i get all related models data without manually writing it?

 $data = $this->Cv->find('first', 
    array(
        'contain' => array('Cv_experience' => array('order' => 'Cv_experience.start_year desc'))));

It sounds like you've been relying on the Model's recursive property. Once you use 'contain', those models that used to come in automatically no longer do, right?

The answer is, you should be using recursive OR contain , not both. If you're using contain , you should set recursive to OFF ( $recursive = -1; ).

As far as which to use, it's HIGHLY recommended to not use recursve at all. Set it to -1 in your AppModel, and use Containable Behavior any time you want additional data. Recursive is bad practice for anything but a simple blog app, and I believe is even being completely removed in Cake 3.

Note on ordering: You cannot order by a contained model. 'Contain' creates multiple queries, so - if you want to do what you're trying, you'll need to use JOINs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM