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.

4

1 回答 1

3

如果您最终以某种方式为该用户拥有多个配置文件,那么由于LEFT JOIN每个配置文件都返回一条记录,您最终将获得多条记录。

这适用于 hasOne 和 belongsTo 关系,因为它们是使用LEFT JOINs 连接数据的关系。

您可以通过手动查看数据库来检查这一点:SELECT * FROM profiles where profiles.userId = 102

于 2012-04-17T16:04:22.613 回答