HABTM桥数据不保存

时间:2014-10-07 03:23:48

标签: php cakephp cakephp-2.3

这是我第一次尝试使用CakePHP中的HABTM,但它并没有像我希望的那样好。

我有表foos和表bars。保存foo后,我想将多个bars与其关联。我试图用bars_foos桥来做这件事。

我希望能够以一种foo方式保存,以及一堆bars之类的内容:

array(2) {
  ["Foo"]=> array(1) {
    ["name"]=> string(7) "someFoo"
  }
  ["Bar"]=> array(4) {
    [0]=> array(1) {
      ["ID"]=> int(3)
    }
    [1]=> array(1) {
      ["ID"]=> int(9)
    }
    [2]=> array(1) {
      ["ID"]=> int(4)
    }
    [3]=> array(1) {
      ["ID"]=> int(15)
    }
  }
}

让我们说使用ID 9创建someFoo ...我希望将以下记录添加到bars_foos表中:

+--------+----------+
| bar_ID | foo_ID   |
+--------+----------+
|      3 |        9 |
|      9 |        9 |
|      4 |        9 |
|     15 |        9 |
+--------+----------+

目前bars_foos表中没有发生任何事情,只有foos表正在使用新创建的" someFoo"进行更新。此桥应该更新的唯一时间是创建新的Foo

我尝试使用我的模型关注the CakePHP documentation

class Foo extends AppModel {
    public $primaryKey = "ID";

    public $hasAndBelongsToMany = array(
        'Bar' =>
            array(
                'className' => 'Bar',
                'joinTable' => 'bars_foos',
                'foreignKey' => 'foo_ID',
                'associationForeignKey' => 'bar_ID'
        )
    );
}

在我的控制器中使用它......

$this->Foo->saveAll($data); //$data looks like the Array above in the first code block

我也根据我在寻找解决方案时遇到的事情,尝试使用我的$data这些格式:

array(1) {
  ["Foo"]=> array(3) {
    ["name"]=> string(7) "FooName"
    ["Bar"]=> array(2) {
      [0]=> array(1) {
        ["ID"]=> int(3)
      }
      [1]=> array(1) {
        ["ID"]=> int(2)
      }
    }
  }
}

array(2) {
  ["Foo"]=> array(1) {
    ["name"]=> string(7) "fooName"
  }
  ["Bar"]=> array(1) {
    ["Bar"]=> array(2) {
      [0]=> array(1) {
        ["ID"]=> int(3)
      }
      [1]=> array(1) {
        ["ID"]=> int(2)
      }
    }
  }
}

得到了相同的结果(创建了新的foo,但没有任何内容插入到bars_foos表中)

1 个答案:

答案 0 :(得分:0)

终于搞定了。看来我们不应该明确地输入相关表的ID键。这种格式对我有用:

array(2) {
  ["Foo"]=>
  array(1) {
    ["name"]=> string(7) "fooName"
  }
  ["Bar"]=> array(1) {
    ["Bar"]=> array(4) {
      [0]=> int(3)
      [1]=> int(2)
      [2]=> int(9)
      [3]=> int(7)
    }
  }
}

并且在桥牌表中给出了我想要的结果:

+--------+----------+
| bar_ID | foo_ID   |
+--------+----------+
|      3 |        9 |
|      2 |        9 |
|      9 |        9 |
|      7 |        9 |
+--------+----------+

这似乎也有同样的效果(没有嵌套Bar id'两次)

array(2) {
  ["Foo"]=>
  array(1) {
    ["name"]=> string(7) "fooName"
  }
    ["Bar"]=> array(4) {
      [0]=> int(3)
      [1]=> int(2)
      [2]=> int(9)
      [3]=> int(7)
    }
}