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.

$data['Post']['id']

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: https://snook.ca/s/687

Want to learn about scaling CSS for large projects?

I'm available for full and half-day workshops on scalable CSS architecture. I can provide on-site training for your team. Interested?
Get in touch.