CakePHP saveAll()函数问题

时间:2010-01-28 05:36:28

标签: php mysql database cakephp

我试图将记录保存到表格以及相关记录中。主表称为引号,它有一个指向表quote_items的hasmany链接。 quote_items属于引用

当我尝试保存时,它会将记录保存在引号中,但不会将记录保存在quote_items中

以下是我的报价添加功能

    function add() {
    if (!empty($this->data)) {
        $this->Quote->create();
        if ($this->Quote->saveAll($this->data)) {
            $this->Session->setFlash(__('The Quote has been saved', true));
            //$this->redirect(array('action'=>'index'));
        } else {
            $this->Session->setFlash(__('The Quote could not be saved. Please, try again.', true));
        }
    }
    $this->Quote->recursive = 2;
    $statuses = $this->Quote->Status->find('list');
    $contacts = $this->Quote->Contact->find('list');
    $this->set(compact('statuses', 'contacts'));
}

引用视图/表单设置

    <?php echo $form->create('Quote', array('action' => 'add'));?>
    <fieldset>
        <legend><?php __('Add Quote');?></legend>
    <?php
        echo $form->input('Quote.name');
        echo $form->input('Quote.revision');
        echo $form->input('Quote.status_id');
        echo $form->input('Quote.contact_id');
        echo $form->input('quote_item.product_id');
        echo $form->input('quote_item.name');
        echo $form->input('quote_item.price');
        echo $form->input('quote_item.description');
        echo $form->input('Quote.totalcost');
    ?>
    </fieldset>
<?php echo $form->end('Submit');?>

提交表单时返回的数组

    Array ( 
    [quote] => Array ( 
                [name] => Test 
                [revision] => 1 
                [status_id] => 1 
                [contact_id] => 1 
                [totalcost] => 123 
              ) 

    [quote_item] => Array ( 
                [product_id] => 1
                [name] => test 
                [price] => 123 
                [description] => tes 1234 
              ) 
) 

这似乎完全遵循cakephp文档中列出的内容,所以我无法解决为什么它不起作用 - http://book.cakephp.org/view/84/Saving-Related-Model-Data-hasOne-hasMany-belongsTo

提前致谢

1 个答案:

答案 0 :(得分:3)

构建表单的正确方法是:

echo $form->input('Quote.name');
...
echo $form->input('QuoteItem.0.product_id');
echo $form->input('QuoteItem.0.name');
...
echo $form->input('QuoteItem.1.product_id');
echo $form->input('QuoteItem.1.name');

生成的数组应如下所示:

array(
    'Quote' => array(
        'name' => 'Test'
        ....
    ),
    'QuoteItem' => array(
        0 => array(
            'product_id' => 1
            'name' => 'test'
            ...
        )
        1 => array(
            'product_id' => 2
            'name' => 'test'
            ...
        )
    )
)

根据命名约定,模型名称是camelized(ModelName,而不是model_name)。此外,由于Quote hasMany QuoteItems,QuoteItem数组需要包含许多QuoteItem数组。希望有道理。 :)