【问题标题】:How to define a Many-To-Many relationship using CakePHP3?如何使用 CakePHP3 定义多对多关系?
【发布时间】:2015-08-10 13:42:49
【问题描述】:

我想在 CakePHP 3 中的三个表之间创建多对多关系。通过在我的控制器和模型中定义这种关系,但我无法解决这个问题。

我的三张表如下:

表一:用户

ID   Name
1    gert
2    henk

表二:衣服

ID   Name
1    jacket
2    jeans

这是我保存用户表和衣服表之间的链接的表。所以现在一个用户可以有多件衣服,不同的衣服可以属于多个用户。

表三:Users_has_clothes

ID   UserId(forKey)   ClothesId(forKey)
1    1                1
2    2                1
3    1                2

我尝试按照 CakePHP 官方网站 Using the ‘through’ Option 的说明进行操作,但我仍然不清楚。

【问题讨论】:

  • 你应该尽量遵循 CakePHP 的命名约定,这样可以省去很多麻烦(比如命名表 users_clothes 和键 user_idclothe_id)。

标签: php mysql cakephp cakephp-3.0


【解决方案1】:

如果您的连接表没有额外字段(在您的示例中看起来没有),则不应使用 through 选项。

如果可以,您应该遵循 CakePHP 命名约定,这意味着您的连接表应该命名为users_clothes,并且它的两个字段应该是user_idclothe_id。有关命名约定的更多详细信息,请参阅CakePHP documentation。使用这些约定,以下代码将起作用:

public class User extends Table {
    public function initialize (array $config) {
         $this->belongsToMany('Clothes');
    }
}
// Same for table Clothe

如果您确实需要保留当前名称,则应添加以下额外选项:

public class User extends Table {
    public function initialize (array $config) {
         $this->belongsToMany('Clothes', [
            'joinTable' => 'Users_has_clothes',
            'foreignKey' => 'UserId', 
            'targetForeignKey' => 'ClotheId'
        ]);
    }
}
// Same for Clothe (switch foreignKey and targetForeignKey)

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2021-11-01
    • 2021-12-26
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多