zen of coding

Filtering results returned by Containable behavior

First of all, let me warn you that what I’m describing here is more or less a hack and is not the most efficient way of handling such things, especially if you are dealing with large volumes of data. It is really here for educational purposes and as food for thought…

Now that I got that out of the way, let’s use our favorite Post HABTM Tag example, and try to do something like this…

We need to get all Posts whose titles start with a ‘t’ and all related Tags, which start with an ‘n’.

Like this:

Related

I’m glad it helped. Regarding the second point, that’s not really true. To get more accurate results you could force a JOIN, which is outlined in some other posts on my blog. That being said, a little filter like this one takes almost no time to implement, but think about how much time you’ve saved just by relying on cake’s ORM alone.
The trade-off is minimal. To say cake forces you to do something is simply not fair, cake offers you to follow best practices, and sometimes it can be hard to “unlearn” bad habits.

flaccid

Thank you for this simple solution!

I do hope that CakePHP will simply support associated table conditions in find() one day as currently this limitation defeats the point of MVC and RDBMS.

The above solution requires nothing special in the controller your modeling will remain exactly the same (if done correctly).

Consulting

During the last twenty years I have helped many startups build amazing technology stacks. Once in a while I consult on a few high-profile projects for Fortune 50 companies.
Let's chat about your next project or
check out our consulting services.