CakePHP查找所有生成返回重复记录(具有相同ID)的SQL。查找列表没有

时间:2012-04-17 15:46:28

标签: mysql cakephp

所以,这段代码如下:

    $friends = $this->find('all',
        array(
            'conditions' => array(
                'User.id' => 102
            ),
            'contain' => 'Profile'
        )
    );

生成此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)

(如果阅读导致你的大脑受伤,则道歉)

此SQL代码选择相同的记录三次。我不知道为什么。它出什么问题了?更重要的是,如何更改CakePHP代码以选择该记录一次而不是三次?

如果它有用:用户属于家庭和hasOne个人资料。

1 个答案:

答案 0 :(得分:3)

如果您以某种方式最终为该用户提供了多个配置文件,由于LEFT JOIN会为每个配置文件返回一条记录,您最终会得到多条记录。

这适用于hasOne和belongsTo关系,因为它们是使用LEFT JOIN来加入数据的关系。

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