gpt4 book ai didi

php - 如何使用 CakePHP3 定义多对多关系?

转载 作者:行者123 更新时间:2023-11-29 07:33:08 25 4
gpt4 key购买 nike

我想在 CakePHP 3 中的三个表之间创建多对多关系。通过在我的 Controller 和模型中定义此关系,但我无法将其关闭。

我的三个表如下:

表一:用户

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 的说明进行操作,但我还是不清楚。

最佳答案

如果您的连接表没有额外的字段(看起来您的示例中没有),则不应使用 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)

关于php - 如何使用 CakePHP3 定义多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com