如何使用 CakePHP3 定义多对多关系?
How to define a Many-To-Many relationship using CakePHP3?
我想在 CakePHP 3 中的三个 table 之间创建多对多关系。通过在我的控制器和模型中定义这种关系,但我无法取消它。
我的三个table如下:
Table一个:用户
ID Name
1 gert
2 henk
Table二:衣服
ID Name
1 jacket
2 jeans
这是我在用户 table 和衣服 table 之间保存 link 的 table。所以现在一个用户可以拥有多件衣服,不同的衣服可以属于多个用户。
Table三个:Users_has_clothes
ID UserId(forKey) ClothesId(forKey)
1 1 1
2 2 1
3 1 2
我已经尝试按照官方 CakePHP 站点的说明进行操作 Using the ‘through’ Option,但我仍然不清楚。
如果您的联接 table 没有额外字段(您的示例中似乎没有),则不应使用 through
选项。
如果可以,您应该遵循 CakePHP 命名约定,这意味着您的连接 table 应该命名为 users_clothes
,并且它的两个字段应该是 user_id
和 clothe_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)
我想在 CakePHP 3 中的三个 table 之间创建多对多关系。通过在我的控制器和模型中定义这种关系,但我无法取消它。
我的三个table如下:
Table一个:用户
ID Name
1 gert
2 henk
Table二:衣服
ID Name
1 jacket
2 jeans
这是我在用户 table 和衣服 table 之间保存 link 的 table。所以现在一个用户可以拥有多件衣服,不同的衣服可以属于多个用户。
Table三个:Users_has_clothes
ID UserId(forKey) ClothesId(forKey)
1 1 1
2 2 1
3 1 2
我已经尝试按照官方 CakePHP 站点的说明进行操作 Using the ‘through’ Option,但我仍然不清楚。
如果您的联接 table 没有额外字段(您的示例中似乎没有),则不应使用 through
选项。
如果可以,您应该遵循 CakePHP 命名约定,这意味着您的连接 table 应该命名为 users_clothes
,并且它的两个字段应该是 user_id
和 clothe_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)