0

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.

3
  • Do you have more than one profile attached to that user? I'd check the database manually SELECT * FROM profiles where profiles.userId = 102. If you have more than one, then the join will return 3 rows and therefore create three records in the array. Apr 17, 2012 at 15:54
  • Brilliant! Add that as an answer and I'll accept it. Thanks.
    – Will
    Apr 17, 2012 at 15:56
  • Cool, glad it helped you figure it out! Apr 17, 2012 at 16:04

1 Answer 1

3

If you somehow end up having more than one Profile for that User, you'll end up with multiple records due to the LEFT JOIN returning 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.