0

我对 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.'));
        }

    }
}
4

1 回答 1

2
$newRecipeItem = new RecipeItem();

这条线没有按照你的想法做。它创建RecipeItem 类的一个实例。但它不会在数据库中进行 INSERT。所以这一行:

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

什么也没做。你可以使用:

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

然后进行保存。

create() 函数文档

于 2012-08-04T22:19:21.820 回答