'fields', 'conditions' and associated models in CakePHP 1.2

Sometimes you see code that tries to do something like this:

$this->Company->find('all', array('conditions' =>array('Profile.name'=>'test'),
                                            'fields'=>array('Profile.id, Profile.name')))

Of course most of the time you’ll hear: “Well, this doesn’t work!”
Yet, some people will disagree: “Works for me!”

So, what’s really going on here?

Whether the above syntax works or not, would depend on your model association. Or, more specifically, whether or not an SQL JOIN is built.

If we assume that Company hasOne Profile, then the above find() will build a query like:

[sourcecode language=”sql”]
SELECT
Profile.id, Profile.name
FROM
`companies`
AS
`Company`
LEFT JOIN
`profiles` AS `Profile`
ON
(`Profile`.`company_id` = `Company`.`id`)
WHERE
`Profile`.`name` = ‘test’
[/cc]

… which is perfectly legal.

Of course if you attempt to do this for hasMany or HABTM, the query is going to fail.
You’ve probably guessed that the same works for belongsTo.

%d bloggers like this: