Use Table Aliases in Custom Queries

You've probably noticed that your normal calls to the model return an array that can be referenced through the model name.


When using custom SQL, though, it'll use the table name. Problem is that your table name uses the pluralized and lowercase version of the model name. The easy fix is to define a custom table alias in your query and now your results can be referenced the same.

SELECT * FROM posts AS Post

I use this when searching. If a user doesn't specify anything, I still return all results using Modelname->findAll() but then if they do enter something, I do some fancy stuff requiring a custom SQL command. Using an alias has meant a consistent resultset to parse through.

Published July 15, 2006 · Updated July 15, 2006
Categorized as CakePHP
Short URL: