Long story short, my database is set up as follows:
Category hasMany Topic
Topic belongsTo Category
Topic hasMany Section
Section belongsTo Topic
Section hasMany Subsection
Subsection belongsTo Section
In my Categories controller I can easily get all my information using a simple find query. However, in my subsections controller for example, I would like to do a complex find query such as:
$conditions = array(
'Subsection.title' => $subsectionname,
'Section.title' => $sectionname,
'Topic.title' => $topicname,
'Category.title => $categoryname
);
$subsection = $this->Subsection->find('first', array(
'conditions' => $conditions,
'recursive' => 3,
));
However, I can only get data about the Subsection and the Section from the query this way. I can access the subsection’s Category in the View by using a call such as $mysubsection['Section']['Topic']['Category']['title']; but I’d ideally like to have all the filtering done in one call. Is this possible?
Figured out a way of doing this. Specifically, I wanted to use really nice looking URLs, so that a user could type in something like http://example.com/aCategoryTitle/aTopicTitle/aSectionTitle/aSubsectionTitle – but this data needs to be validated so that the subsection definitely belongs in the correct category, topic etc..
This is a simple find call which matches all subsections with the correct title and section title.
If there is no subsection matching that criteria, the user is redirected. However, there still may be multiple subsections found with the same section title. Take for example the following URLs:
http://example.com/Cats/Feeding/Food/Meat and http://example.com/Dogs/Feeding/Food/Meat
With these two examples, there would be multiple subsections found which match the above criteria. So we need to carry out some further validation:
This loops through all the Subsections we’ve found, and ensures that their titles, and those of the section, topic and category they belong to, match the URL (as given by
$this->request->params).Probably not the tidiest way of doing it, but it works, and works nicely with my routing. Always happy to take any further suggestions on board, but for now this is working well for me.