简体   繁体   English

在将外键列手动添加到数据库表后,cakephp无法检测到模型关联

[英]cakephp unable to detect model association after manually adding foreign key column to database table

I have two models in a CakePHP application: Users and Groups. 我在CakePHP应用程序中有两个模型:用户和组。 Initially I had not relationships between the two. 最初我没有两者之间的关系。 Now in the database table groups, I manually add the column user_id so that now I have the following relationships between the two: 现在,在数据库表组中,我手动添加了列user_id,以便现在两者之间具有以下关系:

Groups belongsTo Users
Users hasMany Groups

Now after doing this for some reason I keep getting the following error: 现在由于某种原因执行此操作后,我仍然收到以下错误:

1054: Unknown column 'Group.user_id' in 'field list'

I tried to run CakePHP's bake command to see if Cake will automatically detect the relationship between my two models. 我试图运行CakePHP的bake命令来查看Cake是否会自动检测两个模型之间的关系。 When I try to bake the User model, CakePHP does not even detect that there is a hasMany relationship between User and Group. 当我尝试烘焙User模型时,CakePHP甚至没有检测到User和Group之间存在hasMany关系。 Any idea why is this happenning and how I can fix this please? 知道为什么会这样吗,请问如何解决?

Thank you 谢谢

Perhaps I am misunderstanding how you want your associations, but I would imagine that: 也许我误会了您希望如何建立联系,但我会想到:

A User belongsTo a Group 用户属于组

A Group hasMany Users 群组有许多用户

Example User model: 用户模型示例:

class User extends AppModel {
    public $belongsTo = array(
        'Group' => array(
            'className' => 'Group',
            'foreignKey' => 'group_id'
        )
    );
}

Example Group model: 组模型示例:

class Group extends AppModel {
    public $hasMany = 'User';
} 

Your Users table will need a group_id field. 您的用户表将需要一个group_id字段。

All of this is assuming that you want one group per user. 所有这些都是假设您希望每个用户一个组。 If you want Users to have multiple groups then you may wish to define a HABTM relationship between Users and Groups, or perhaps researching Access Control Lists may point you in a better direction (I have yet to utilize Cake's ACL component yet). 如果希望用户具有多个组,则可能希望定义用户和组之间的HABTM关系,或者研究访问控制列表可能会为您指明一个更好的方向(我尚未使用Cake的ACL组件)。

Either way, I highly suggest reviewing the Cakebook page on Associations: Linking Models Together . 无论哪种方式,我都强烈建议您查看“ 关联:链接模型在一起”上的Cakebook页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM