0

更新#2——找到的解决方案: 原来我使用了这个查找:

$this->User->Group->find(....)

不是我需要的。要提取我需要使用的用户组:

$this->User->find('all',array('conditions' => array('User.id' => $user_id)));

</更新#2><问题>

我正在尝试在Users表和Groups表之间建立 HABTM 关系。问题是,当我发出这个电话时,我:

$this->User->Group->find('list');

发出的查询是:

SELECT [Group].[id] AS [Group__id], [Group].[name] AS [Group__name] FROM [groups] AS [Group] WHERE 1 = 1

在这一点上,我只能假设我已经错误地定义了我的关系,因为我希望行为groups_users按照约定使用在数据库上定义的表。我的人际关系:

class User extends AppModel {
        var $name = 'User';
        //...snip...
    var $hasAndBelongsToMany = array(
        'Group' => array(
            'className'             => 'Group',
            'foreignKey'            => 'user_id',
            'associationForeignKey' => 'group_id',
            'joinTable'             => 'groups_users',
            'unique'                => true,
        )
    );
        //...snip...
}

class Group extends AppModel {
    var $name = 'Group';
    var $hasAndBelongsToMany = array ( 'User' => array(
        'className'             => 'User',
        'foreignKey'            => 'group_id',
        'associationForeignKey' => 'user_id',
        'joinTable'             => 'groups_users',
        'unique'                => true,
    ));
}

我对 HABTM 的理解是错误的吗?我将如何实现这种多对多关系,我可以使用 CakePHP 查询groups_users表,以便返回当前经过身份验证的用户关联的组列表?

更新

应用ndm建议的更改后,我仍然收到一个大数组返回(太大而无法发布),它返回所有组,然后'User'如果用户具有该组的成员资格,则返回一个元素。我再次查看了 CakePHP 使用的查询:

SELECT 
    [User].[id] AS [User__id], 
    [User].[username] AS [User__username], 
    [User].[password] AS [User__password], 
    [User].[email] AS [User__email], CONVERT(VARCHAR(20), 
    [User].[created], 20) AS [User__created], CONVERT(VARCHAR(20), 
    [User].[modified], 20) AS [User__modified], 
    [User].[full_name] AS [User__full_name], 
    [User].[site] AS [User__site], 
    [GroupsUser].[user_id] AS [GroupsUser__user_id], 
    [GroupsUser].[group_id] AS  [GroupsUser__group_id], 
    [GroupsUser].[id] AS [GroupsUser__id] 
FROM 
    [users] AS [User] JOIN 
        [groups_users] AS [GroupsUser] ON (
        [GroupsUser].[group_id] IN (1, 2, 3, 4, 5) AND 
        [GroupsUser].[user_id] = [User].[id]
    ) 

有没有一种简单的方法来改进它,以便我只收到我拥有成员资格的条目的组 ID 和名称?我正在考虑使用:

array('conditions'=>array('GroupsUser.user_id'=>$user_id))

...但我收到关于组表的 sql 错误:

SELECT TOP 1 [Group].[name] AS [Group__name], CONVERT(VARCHAR(20), [Group].[created], 20) AS [Group__created], CONVERT(VARCHAR(20), [Group].[modified], 20) AS [Group__modified], [Group].[id] AS [Group__id] FROM [groups] AS [Group] WHERE [GroupsUser].[user_id] = 36 ORDER BY (SELECT NULL) 
4

1 回答 1

1

我想你只是误解了listfind 类型是做什么的。

查询完全没问题,list查找类型仅用于检索单个模型的记录列表,其中模型主键用作索引,显示字段用作值。

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list

于 2012-11-05T22:56:58.830 回答