相同表的多个HABTM关系 - Cake 3

Gau*_*rav 1 cakephp cakephp-3.0

我的cakephp 3应用程序中有2个表 - 项目颜色.一个Item也可以有多个Primary Colors和Secondary Colors.所以,我创建了2个联结表 - items_primary_colorsitems_secondary_colors.两者都有相同的模式 - item_idcolor_id(加入Items和Colors表)我不知道如何在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'
]);
Run Code Online (Sandbox Code Playgroud)

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

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

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

)
Run Code Online (Sandbox Code Playgroud)

它不起作用.我应该怎么处理这个?

Gre*_*idt 5

您需要为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'
]);
Run Code Online (Sandbox Code Playgroud)