CakePHP find with “contain”

2019-09-06 12:49发布

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'))));

1条回答
仙女界的扛把子
2楼-- · 2019-09-06 13:30

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.

查看更多
登录 后发表回答