Cakephp通过find选项无法正常工作

时间:2011-10-29 07:47:38

标签: php mysql cakephp

我正在尝试将Users表加入到我的curent hasMany Through表中,该表具有兴趣和用户模型ID。

以下是带有选项的查询查询:

$params = array(
                    'fields' => array('*', 'COUNT(DISTINCT(InterestsUser.interest_id)) as interest_count'),
                    'limit' => 15,
                    'recursive' => -1,
                    'offset' => $offset,
                    'conditions' => array('InterestsUser.interest_id' => $conditions),
                    'group' => array('InterestsUser.user_id'),
                    'order' => array('interest_count DESC', 'InterestsUser.user_id ASC', 'InterestsUser.interest_id ASC'),
                        'joins' => array(
                            array('table' => 'users',
                                'alias' => 'User',
                                'type' => 'LEFT',
                                'conditions' => array(
                                    'User.id' => 'InterestsUser.user_id',
                                )
                            )
                        )
                    );

            $results = $this->InterestsUser->find('all', $params);

这会返回InterestsUser表,但不会返回Users表的任何值。它只返回字段名称。

可能出现什么问题?

更新 好的,上面是生成我从Cake的数据源sql log获得的SQL:

SELECT *, COUNT(DISTINCT(InterestsUser.interest_id)) as interest_count 
FROM `interests_users` AS `InterestsUser` 
LEFT JOIN users AS `User` ON (`User`.`id` = 'InterestsUser.user_id')  
WHERE `InterestsUser`.`interest_id` IN (3, 2, 1)  
GROUP BY `InterestsUser`.`user_id`  
ORDER BY `interest_count` DESC, `InterestsUser`.`user_id` ASC, `InterestsUser`.`interest_id` ASC  
LIMIT 15

为什么users表值只对所有字段返回NULL?

更新

好的我试过下面但是这很好......我在这里缺少什么!! ??

SELECT * , COUNT( DISTINCT (
interests_users.interest_id
) ) AS interest_count
FROM interests_users
LEFT JOIN users ON ( users.id = interests_users.user_id ) 
WHERE interests_users.interest_id
IN ( 1, 2, 3 ) 
GROUP BY interests_users.user_id
ORDER BY interest_count DESC 
LIMIT 15

1 个答案:

答案 0 :(得分:1)

连接条件的数组语法应如下所示

array('User.id = InterestsUser.user_id')

而不是array('User.id' => 'InterestsUser.user_id')。有关更多信息,请参阅http://book.cakephp.org/view/1047/Joining-tables