繁体   English   中英

cakePHP 3.0 HABTM关系保存数据

[英]cakePHP 3.0 HABTM relations save data

我想在cakePHP 3.0中制作本教程http://miftyisbored.com/complete-tutorial-habtm-relationships-cakephp/

我有3张桌子:食谱,配料和Ingredients_recipes。

制作食谱时,我想选择配料。 然后,我想将recipe_id和Ingredient_id存储在Ingredients_recipes表中,但是这样做没有成功。 我认为RecipesController中出了点问题。 有人可以帮助我或指出正确的方向吗?

问题:

$ingredients = $this->Recipes->Ingredients->find('list', ['limit' => 200]);
// => THIS GIVES ME THE MESSAGE "The recipe could not be saved. Please, try again."

$ingredients = $this->Ingredients->find('list', ['limit' => 200]);
// => THIS GIVES ME THE ERROR "Call to a member function find() on boolean"

当我做var dump时(使用此$ this-> Recipes-> Ingredients-> find时),我得到了:

array(3) { 
   ["recipe_name"]=> string(4) "Test" 
   ["recipe_description"]=> string(4) "Test" 
   ["Recipe"]=> array(1) { 
      ["Ingredient"]=> array(1) { [0]=> string(1) "1" } 
   } 
}

表:

CREATE TABLE `recipes` (
  `recipe_id` int(11) NOT NULL auto_increment,
  `recipe_name` varchar(255) NOT NULL,
  `recipe_description` text NOT NULL,
  PRIMARY KEY  (`recipe_id`)
);
CREATE TABLE `ingredients` (
  `ingredient_id` int(11) NOT NULL auto_increment,
  `ingredient_name` varchar(255) NOT NULL,
  `ingredient_description` text NOT NULL,
  PRIMARY KEY  (`ingredient_id`)
);
CREATE TABLE `ingredients_recipes` (
  `ingredient_id` int(11) NOT NULL,
  `recipe_id` int(11) NOT NULL,
  PRIMARY KEY  (`ingredient_id`,`recipe_id`)
);

这是我的代码如下:

模型>实体:

食谱

class Recipe extends Entity
{
    protected $_accessible = [
        'recipe_id' => true,
        'recipe_name' => true,
        'recipe_description' => true,
    ];
}

成分

class Ingredient extends Entity
{
    protected $_accessible = [
        'ingredient_id' => true,
        'ingredient_name' => true,
        'ingredient_description' => true,
    ];
}

IngredientsRecipe

class IngredientsRecipe extends Entity
{
    protected $_accessible = [
        'ingredient' => true,
        'recipe' => true,
    ];
}

型号>表格:

RecipesTable

class RecipesTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('recipes');
        $this->displayField('recipe_name');
        $this->primaryKey('recipe_id');

        $this->belongsTo('Recipes', [
            'foreignKey' => 'recipe_id',
            'joinType' => 'INNER'
        ]);

        $this->belongsToMany('Ingredients', [
            'className' => 'Ingredients',
            'joinTable' => 'ingredients_recipes',
            'foreignKey' => 'recipe_id',
            'targetForeignKey' => 'ingredient_id' 
        ]);
    }
    public function validationDefault(Validator $validator)
    {
        $validator
            ->requirePresence('recipe_name', 'create')
            ->notEmpty('recipe_name')

            ->requirePresence('recipe_description', 'create')
            ->notEmpty('recipe_description')

            ->requirePresence('Ingredients', 'create')
            ->notEmpty('Ingredients');

        return $validator;
    }
}

IngredientsTable

class IngredientsTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('ingredients');
        $this->displayField('ingredient_name');
        $this->primaryKey('ingredient_id');

        $this->belongsTo('Ingredients', [
            'foreignKey' => 'ingredient_id',
            'joinType' => 'INNER'
        ]);

        $this->belongsToMany('Recipies', [
            'className' => 'Recipies',
            'joinTable' => 'ingredients_recipes',
            'foreignKey' => 'ingredient_id',
            'targetForeignKey' => 'recipe_id' 
        ]);
    }
}

IngredientsRecipesTable

class IngredientsRecipesTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('ingredients_recipes');

        $this->displayField('recipe_id');

        $this->primaryKey(['recipe_id', 'ingredient_id']);

        $this->belongsTo('Recipies', [
            'foreignKey' => 'recipe_id',
            'joinType' => 'INNER'
        ]);

        $this->belongsTo('Ingredients', [
            'foreignKey' => 'ingredient_id',
            'joinType' => 'INNER'
        ]);
    }

控制器:

的RecipesController

public function add()
{
    $recipe = $this->Recipes->newEntity();
    if ($this->request->is('post')) {
        $recipe = $this->Recipes->patchEntity($recipe, $this->request->data);
        // var_dump($this->request->data);
        if ($this->Recipes->save($recipe)){
            $this->Flash->success('The recipe has been saved.');
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error('The recipe could not be saved. Please, try again.');
        }
    }
    $recipes = $this->Recipes->find('list', ['limit' => 200]);

    $ingredients = $this->Recipes->Ingredients->find('list', ['limit' => 200]);
    // => THIS GIVES ME THE MESSAGE "The recipe could not be saved. Please, try again."
    $ingredients = $this->Ingredients->find('list', ['limit' => 200]);
    // => THIS GIVES ME THE ERROR "Call to a member function find() on boolean"

    $this->set(compact('recipe', 'recipes', 'ingredients'));
    $this->set('_serialize', ['recipe']);
}

模板>食谱

add.ctp

<?= $this->Form->create($recipe); ?>
    <fieldset>
        <legend><?= __('Add Recipe') ?></legend>
        <?php
            echo $this->Form->input('recipe_name', array(
                'label' => 'Name'
                )
            );
            echo $this->Form->input('recipe_description', array(
                'label' => 'Description'
                )
            );

            echo $this->Form->input('Recipes.Ingredients', ['multiple'=>true]);
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>

也许本教程可以对您有所帮助: http : //book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html

它确切地解释了如何设置HABTM关系,如何将标签添加到书签等等。

祝你好运,编码愉快:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM