我对 CakePHP 很陌生,所以我的问题希望很容易回答。
我想创建一个表单来同时添加新配方和配方项。我怎么做?
我的数据库中有三个表:recipes、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')); ?>
配方控制器:
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.'));
}
}
}