更新#2 - 解决方案: 结果我使用了这个查找:
$this->User->Group->find(....)
不是我需要的。要拉出我需要使用的用户组:
$this->User->find('all',array('conditions' => array('User.id' => $user_id)));
< / UPDATE#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))
...但我在groups表上收到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)
答案 0 :(得分:1)