Tags in Social Tags

Complex Queries in CakePHP 2.x

With CakePHP, a MVC-based PHP framework, it is usually very easy to retrieve data from the database table underlying a specific model, as well as in case the tables are connected with each other through their respective model declarations, as these tables are then joined automatically.
However, when one wants to join multiple tables within one query and they are not connected through their models (which occurs quite often), then there nevertheless has to be a way to join the desired tables to get the respective data. The goal is to find a way in CakePHP to accomplish this task.

Here two tables are joined on a common field (e.g. the ID field), if one wants to add additional tables, these can be added easily by just appending them to the 'joins' array. This approach is the preferred one, since it uses only the native CakePHP way of creating SQL statements and thus benefits from all inbuilt security measures.

2)

The second approach would be to use the capability of CakePHP to create queries with raw SQL, however, this approach is discouraged, since it is potentially vulnerable to SQL injection, as the responsibility for handling such a case is transferred from the framework to the user. Still, it shall be shown here. It basically works like this: