0
我是CakePHP的新手,所以我的問題很容易回答。保存數據到數據庫
我想創建一個表單,用於同時添加新配方和recipeitem。我怎麼做?
我有三個表在我的數據庫:食譜,recipeitems和recipes_recipeitems;
eg. Recipe.title
Recipe.cookingtime
Recipeitem.name
我嘗試了以下操作,但它只創建了一個Recipepart而沒有設置它的名稱或recipe_id。
形式:
<?php echo $this->Form->create('Recipe'); ?>
<fieldset>
<legend><?php echo __('Create recipe'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('cooking_time');
echo $this->Form->input('RecipeitemName');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
RecipeController:
App::import('model','RecipeItem');
class RecipesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->request->data['Recipe']['user_id'] = $this->Auth->user('id');
$this->request->data['RecipeItem']['name'] = $this->request->data['Recipe']['RecipeitemName'];
$newRecipeItem = new RecipeItem();
$this->Recipe->create();
if ($this->Recipe->save($this->request->data)) {
$this->Session->setFlash(__('The recipe has been saved'));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The recipe could not be saved. Please, try again.'));
}
$this->request->data['RecipeItem']['recipe_id'] = $this->Recipe->id;
if ($newRecipeItem->save($this->request->data)) {
$this->Session->setFlash(__('The recipeItem has been saved'));
$this->redirect(array('action' => 'index'));
} else{
$this->Session->setFlash(__('The recipeItem could not be saved. Please, try again.'));
}
}
}
您的關聯在您的模型中設置是否正確? – Julien 2012-08-04 21:39:26