So, this code below:
$friends = $this->find('all',
array(
'conditions' => array(
'User.id' => 102
),
'contain' => 'Profile'
)
);
Generates this SQL:
SELECT `User`.`id`, `User`.`sForceId`, `User`.`householdId`,
`User`.`householdSForceId`, `User`.`username`, `User`.`primaryUser`, `User`.`password`,
`User`.`firstName`, `User`.`lastName`, `User`.`dateOfBirth`, `User`.`email`,
`User`.`preferredEmail`, `User`.`phone`, `User`.`preferredPhone`, `User`.`homePhone`,
`User`.`workPhone`, `User`.`mobilePhone`, `User`.`ethnicity`, `User`.`ethnicityOther`,
`User`.`religion`, `User`.`religionOther`, `User`.`active`, `User`.`adminStatus`,
`User`.`group`, `User`.`created`, `User`.`modified`, `Profile`.`id`,
`Profile`.`userId`, `Profile`.`aboutMe`, `Profile`.`picture`, `Profile`.`created`,
`Profile`.`modified`, `Profile`.`lat`, `Profile`.`lng` FROM `users` AS `User` LEFT JOIN
`profiles` AS `Profile` ON (`Profile`.`userId` = `User`.`id`) WHERE `User`.`id` = (102)
(apologies if reading that makes your brain hurt)
This SQL code selects the same record three times. I have no idea why. What’s wrong with it? More importantly, how do I change my CakePHP code to select that record one time instead of three times?
In case it’s helpful: User belongsTo Household and hasOne Profile.
If you somehow end up having more than one Profile for that User, you’ll end up with multiple records due to the
LEFT JOINreturning a record for each profile.This applies to hasOne and belongsTo relationships as they are the ones that use
LEFT JOINs to join the data.You can check for this by looking at the database manually:
SELECT * FROM profiles where profiles.userId = 102