正在将数据保存到数据库


Saving data to database

我是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')); ?>

配方控制器:

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.'));
        }
    }
}
$newRecipeItem = new RecipeItem();

这句话不是你想的那样。它创建RecipeItem类的一个实例。但它不会在数据库中进行INSERT。所以这行:

$newRecipeItem->save($this->request->data)

什么也不做。您可以使用:

$this->Recipe->RecipeItem->create();

然后进行保存。

create()函数文档