同一张表的多个 HABTM 关系 - Cake 3

multiple HABTM relationships for same tables - Cake 3

我的 cakephp 3 应用程序中有 2 个表 - ItemsColors。一个项目也可以有多个原色和副色。 因此,我创建了 2 个联结表 - items_primary_colorsitems_secondary_colors。 两者具有相同的架构 - item_idcolor_id(加入项目和颜色表) 我不确定如何在 TableModel 中指定这些关系以及如何格式化表单数据以保存两种类型的颜色。 我的 ItemTable.php 代码有 -

$this->belongsToMany('Colors', [
    'foreignKey' => 'item_id',
    'targetForeignKey' => 'color_id',
    'joinTable' => 'items_primary_colors'
]);
$this->belongsToMany('Colors', [
    'foreignKey' => 'item_id',
    'targetForeignKey' => 'color_id',
    'joinTable' => 'items_secondary_colors'
]);

而且,我正在以这种方式格式化表单数据 -

[primary_colors] => Array
(
    [_ids] => Array
    (
        [0] => 2
    )
)

[secondary_colors] => Array
(
    [_ids] => Array
    (
        [0] => 3
    )

)

它不工作。我该如何处理?

您需要为 belongsToMany 关系指定不同的名称。尝试

$this->belongsToMany('PrimaryColors', [
    'className' => 'Colors',
    'foreignKey' => 'item_id',
    'targetForeignKey' => 'color_id',
    'joinTable' => 'items_primary_colors'
]);
$this->belongsToMany('SecondaryColors', [
    'className' => 'Colors',
    'foreignKey' => 'item_id',
    'targetForeignKey' => 'color_id',
    'joinTable' => 'items_secondary_colors'
]);