0

我有一个add行动表格ProductsController,根据大小有很多价格。我试图先保存产品,然后在 foreach 循环中保存价格。

有些如何saveAllsaveAssociated没有工作。

public function add() {
        if ($this->request->is('post')) {
            $this->Product->create();
            $product = $this->Product->save($this->request->data);

            if (!empty($product)) {
                $product_id = $this->Product->getInsertID();
                $prices = $this->request->data['Product']['price'];

                foreach ($prices as $price) {
                    $price['product_id'] = $product_id;
                    $this->Product->Price->save($price);
                     $this->Product->Price->id = false;
                }

                $this->Session->setFlash('The product has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add the product.');
            }
        }
    }

模型看起来像

class Product extends AppModel {        
   ...
   public $hasMany = array(
      'Price' => array(
              'className' => 'Price',           
                 )
   );


class Price extends AppModel {

    public $belongsTo = array(
        'Product' => array(
            'className' => 'Product',
            'foreignKey' => 'product_id', 
        )
    );
}
4

1 回答 1

1

您可以saveAssociated()按照文档使用

但是你的视图应该是这样的:

echo $this->Form->create('Product', array('action' => 'add'));
    echo $this->Form->input('Product.name', array('label' => 'Name'));
    echo $this->Form->input('Product.description', array('label' => 'Description'));

    echo $this->Form->input('Price.0.amount', array('label' => 'Amount'));
    echo $this->Form->input('Price.0.price', array('label' => 'Price'));
echo $this->Form->end('Add');
于 2013-01-22T12:31:47.173 回答