cakephp HABTM同型号

时间:2012-10-07 21:53:55

标签: php cakephp cakephp-2.0 has-and-belongs-to-many cakephp-appmodel

我在cakephp 2.0中开发了一个网站 我想与同一模型建立HABTM关系:产品可以有更多产品。

我想在这种模式下进入我的模型:

class Product extends AppModel {
    public $name = 'Product';
    public $useTable = 'products';
    public $belongsTo = 'User';
    public $actsAs = array('Containable');

        public $hasAndBelongsToMany = array(
        'Ingredient' => array(
            'className' => 'Product',
            'joinTable' => 'ingredients_products',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'ingredient_id', 
            'unique' => true
        )
    );

} 

我的关系是否正确?但是我要在我的表产品中插入字段product_id和ingredient_id吗? 如何使用表单保存数据?我知道如何使用HABTM保存数据,但我从未对同一个表做过HABTM。

1 个答案:

答案 0 :(得分:1)

你的关系很好。您所写的内容将创建一个产品模型,该产品模型可以包含任意数量的成分,并允许成分属于任意数量的产品。

保存时,您必须简单地将成分视为另一种型号。保存HABTM的CakePHP示例与将2个不同模型关联的同一模型一样有效:http://book.cakephp.org/2.0/en/models/saving-your-data.html

因此,如果您将多个成分保存到产品中,则Array结构将如下所示:

  

阵列(
  [0] =>阵列(
  产品=>数组(
  id => 1
  ),
  成分=>数组(
  id => 18个
  )
  ),
  1 =>阵列(
  产品=>数组(
  id => 1
  ),
  成分=>数组(
  id => 23个
  )
  )
  // ...   )

由您决定如何在表单中捕获它,但上面提供的链接中使用的表单示例应该正确管理。

相关问题