我对 CakePHP 如何处理它的数据库关系有点困惑。

对于 hasOne 关系,根据 documentation :

“用户有一个个人资料”
User hasOne Profile -> profiles.user_id

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Profile] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
            [created] => 2007-05-01 10:31:01
        )
)

但这不是一对多的关系吗?

例如(我制作了这些表格来说明我的困惑):



在这种情况下,有 2 个配置文件属于同一用户。这不意味着用户有许多个人资料吗?

如果“User hasOne Profile”是更有意义的



那么这将是“User hasOne Profile”但“Profile hasMany User”?

我不确定我是否正确理解了这一点。

最佳答案

在文档的示例中,当它说用户有一个配置文件时,这意味着用户只能有一个配置文件。

因此是一对一的关系。您可以选择在何处放置外键,他们更喜欢在 profile 表上使用它。

你的图片是错误的。在您的情况下,它将是一对多。这是一个 hasMany + belongsTo
他们只是决定每个用户只有一个配置文件,如果你想每个用户有多个配置文件,那么它不会是 hasOne 。那是你的决定。

关于php - CakePHP:一对一的关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17862125/

10-13 08:53