1

我有一个用 cakephp 2.0 开发的网站。我有一个关系HABTM到同一个模型是这样的:

class Product extends AppModel {
    public $name = 'Product';
    public $useTable = 'products';
    public $belongsTo = 'User';
    public $actsAs = array('Containable');
        public $hasAndBelongsToMany = array(
        'Product' => array(
            'className' => 'Product',
            'joinTable' => 'ingredients_products',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'ingredient_id', 
            'unique' => false
        )
    );

}

我想用这样的简单形式将记录保存到我的视图中:

echo $this->Form->create('IngredientProduct', array ('class' => 'form', 'type' => 'file'));

        foreach ($product as $prod) {
            echo '<div>'.$prod['ProductAlias']['alias'].'</div>';  
            echo $this->Form->input('IngredientProduct.product_id', array ('type'=>'text', 'value'=>  $prod['ProductAlias']['id'], 'label'=> false, 'id' => 'id'));
        }

        $select = '<select  name="data[IngredientProduct][ingredient_id]" id="[IngredientProductIngredientId">';
        foreach ($other_product as $prod2) {
            $select .= '<option value="'.$prod2['ProductAlias']['id'].'">'.$prod2['ProductAlias']['alias'].'</option>';
        }
        $select .= '</select><br>';
        echo($select);

        echo $this->Form->submit('Collega', array('id'=>'link_product'));
        echo $this->Form->end();

在我的控制器中,我以这种模式保存:

if ($this->Product->saveAll($this->request->data)){
                $this->Session->write('flash_element','success');
                $this->Session->setFlash ('Prodotto collegato con successo.');
                //$this->redirect(array('action'=>'edit',$alias));
            }
            else{
                $this->Session->write('flash_element','error');
                $this->Session->setFlash('Errore di salvataggio activity');
            }

当我要查看数据库时,我看到成分:id 设置良好,但 product_id 为 0。我已经调试了我的 request->data,这是数组:

array(
    'IngredientProduct' => array(
        'product_id' => '1',
        'ingredient_id' => '2'
    )
)

我打印了 cakephp 创建的 sql 查询:

INSERT INTO `db`.`ingredients_products` (`product_id`, `ingredient_id`, `modified`, `created`) VALUES ('', 2, '2012-10-09 23:19:22', '2012-10-09 23:19:22')

为什么 product_id 为 null 而不是 1?有人能帮我吗?谢谢

4

1 回答 1

1

我认为这条线是错误的:

$this->Product->saveAll($this->request->data);

尝试:

$this->IngredientProduct->saveAll($this->request->data);

因为您的表单似乎询问关系的数据,而不是新产品。

于 2012-10-10T14:27:05.010 回答