table 和它自己之间的 BelongstoMany 关系
BelongstoMany relationship between a table and itself
我有一个包含 table 用户的数据库,我需要存储有关它们之间一种关系的信息:有权管理其他用户的用户。此外,那些被管理的用户也可以是管理员,因此任何用户都可以是管理员或由包括他们自己在内的任何其他用户管理(2 个用户可以互为管理员)。
所以我想到的唯一想法是用这些字段创建一个 "join" table:
manager_id (key field that links to a user_id)
managed_id (key field too that links to a user_id as well)
但是同一个table之间的join table,会产生什么样的关系呢?
用户->belongsToMany('Users') ??
这样可以吗?
(在 ndm 回答后编辑)
我在使用 ndm 告诉我的方法时遇到错误。
所以,在 UsersTable.php 我现在有:
$this->belongsToMany('Managers', [
'className' => 'Users',
'foreignKey' => 'manager_id',
'targetForeignKey' => 'user_id'
]);
在数据库中 "test.sql" table managers_users 有 2 个字段:
manager_id
user_id
两个关键字段
但是当我尝试从 UsersController.php 查询时:
$query = $this->Users->find()
->contain(['Managers'])
->all()
;
我收到错误:SQLSTATE[42S02]:找不到基础 table 或视图:1146 Table 'test.users_users' 不存在
有什么帮助吗?
连接 table 通常涉及 belongsToMany
关联,它基本上是 hasMany
和 belongsTo
的组合,也可以手动表示为, 也可以用 hasOne
和 belongsTo
来表示, 这真的取决于你的应用程序的需要, 所以你可能应该先评估你的应用程序在什么情况下需要如何查询数据, 然后再去从那里开始。
一般来说,自关联很好(请参阅 Cookbook 关联章节中的介绍),所以是的,主要是没问题,但是您需要 setup/configure 一些不同的东西才能顺序为了让它正常工作,那就是你需要使用一个唯一的别名,例如 Managers
而不是 Users
,然后你的外键字段需要适应约定,即user_id
(托管用户)和 manager_id
(管理用户),或者您必须在关联配置中相应地配置它们:
$this->belongsToMany('Managers', [
'className' => 'Users',
//'foreignKey' => 'managed_id',
//'targetForeignKey' => 'manager_id'
]);
另见
我有一个包含 table 用户的数据库,我需要存储有关它们之间一种关系的信息:有权管理其他用户的用户。此外,那些被管理的用户也可以是管理员,因此任何用户都可以是管理员或由包括他们自己在内的任何其他用户管理(2 个用户可以互为管理员)。
所以我想到的唯一想法是用这些字段创建一个 "join" table:
manager_id (key field that links to a user_id)
managed_id (key field too that links to a user_id as well)
但是同一个table之间的join table,会产生什么样的关系呢?
用户->belongsToMany('Users') ??
这样可以吗?
(在 ndm 回答后编辑)
我在使用 ndm 告诉我的方法时遇到错误。
所以,在 UsersTable.php 我现在有:
$this->belongsToMany('Managers', [
'className' => 'Users',
'foreignKey' => 'manager_id',
'targetForeignKey' => 'user_id'
]);
在数据库中 "test.sql" table managers_users 有 2 个字段:
manager_id
user_id
两个关键字段
但是当我尝试从 UsersController.php 查询时:
$query = $this->Users->find()
->contain(['Managers'])
->all()
;
我收到错误:SQLSTATE[42S02]:找不到基础 table 或视图:1146 Table 'test.users_users' 不存在
有什么帮助吗?
连接 table 通常涉及 belongsToMany
关联,它基本上是 hasMany
和 belongsTo
的组合,也可以手动表示为, 也可以用 hasOne
和 belongsTo
来表示, 这真的取决于你的应用程序的需要, 所以你可能应该先评估你的应用程序在什么情况下需要如何查询数据, 然后再去从那里开始。
一般来说,自关联很好(请参阅 Cookbook 关联章节中的介绍),所以是的,主要是没问题,但是您需要 setup/configure 一些不同的东西才能顺序为了让它正常工作,那就是你需要使用一个唯一的别名,例如 Managers
而不是 Users
,然后你的外键字段需要适应约定,即user_id
(托管用户)和 manager_id
(管理用户),或者您必须在关联配置中相应地配置它们:
$this->belongsToMany('Managers', [
'className' => 'Users',
//'foreignKey' => 'managed_id',
//'targetForeignKey' => 'manager_id'
]);
另见