To close. Try the following:
$this->set('posts', $this->Category->find( 'first', array( 'conditions' => array( 'Category.uri' => $uri ), 'contain' => array('Post' => array('Category')) ) ));
Tangent
Controller spelling code, for example, has problems:
- It inflates your controller methods and makes your controllers less readable.
- This prevents reuse of business logic among your different controllers.
You can satisfactorily fix these problems by moving the search call to the model method:
// Categories Controller $this->set('posts', $this->Category->get_posts_with_cats($uri)); // Category Model function get_posts_with_cats($uri) { $this->find('first', array( 'conditions' => array('Category.uri' => $uri), 'contain' => array('Post' => array('Category')) )); }
It makes your code More Awesome :
- The controller is nice and skinny and super readable.
- Now you can call the same method from any related model. So, for example, in
PostsController you could call: $this->Post->Category->get_posts_with_cats($uri); . Now your code is DRY .
Touch # 2
After you learn how to embed constrained models, as I showed you, you may be tempted to do something like this in the future:
$this->find('first', array( 'conditions' => array('Category.uri' => $uri), 'contain' => array( 'Post' => array( 'Category' => array( 'Tag' => array('Author') ) ) ) ));
Good news? . You will get the required model data from the above method (so far you have identified all these relationships).
Scary news? CakePHP does not know how to optimize queries for such deep associations. Thus, as your database grows, you will receive dozens (if not hundreds (if not thousands) of SELECT queries to the database, effectively leading your application to a crawl (if not stopped).
The good people who develop CakePHP are working on safer behavior for CakePHP 2.0, but you have to wait until you get this level of accuracy.