我对CakePHP很陌生,所以我的问题很容易回答。
我想创建一个表单,用于同时添加新配方和配方。我该怎么做?
我的数据库中有三个表:食谱,食谱和食谱_食谱;
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.'));
}
}
}
答案 0 :(得分:2)
$newRecipeItem = new RecipeItem();
这条线没有按你的想法行事。它创建RecipeItem类的实例。但它不会在数据库中生成INSERT。所以这一行:
$newRecipeItem->save($this->request->data)
什么都不做。你可以使用:
$this->Recipe->RecipeItem->create();
然后进行保存。