我有一个add
操作表单ProductsController
,根据大小有很多价格。我试图首先保存产品,然后在foreach循环中保存价格。
有些saveAll
或saveAssociated
无效。
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',
)
);
}
答案 0 :(得分:1)
您可以按documentation
使用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');