cakephp HABTM保存空字段

时间:2012-10-09 21:26:30

标签: 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(
        '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-&gt;数据,这是数组:

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? 有人能帮我吗? 感谢

1 个答案:

答案 0 :(得分:1)

我认为这一行是错误的:

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

尝试:

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

因为您的表单似乎要求数据提供关系,而不是新产品。