我有一个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',
)
);
}