CakePHP 2.1:HABTM保存关联并保留现有数据


CakePHP 2.1 : HABTM saveAssociated and keep exists data

我在保存关联和存在条目时遇到了一点问题:(

模型:

成分.php

<?php
class Ingredient extends AppModel {
    public $name = 'Ingredient';
    public $hasMany = array('IngredientsRecipes');
    public $hasAndBelongsToMany = array(
        'Recipe' =>
            array(
                'className'              => 'Recipe',
                'joinTable'              => 'ingredients_recipes',
                'foreignKey'             => 'ingredient_id',
                'associationForeignKey'  => 'recipe_id',
                'unique'                 => 'keepExisting',
                'conditions'             => '',
                'fields'                 => '',
                'order'                  => '',
                'limit'                  => '',
                'offset'                 => '',
                'finderQuery'            => '',
                'deleteQuery'            => '',
                'insertQuery'            => ''
            )
    );
 }

食谱.php

<?php
class Recipe extends AppModel {
    public $name = 'Recipe';
    public $hasMany = array('IngredientsRecipes');
    public $hasAndBelongsToMany = array(
        'Ingredient' =>
            array(
                'className'              => 'Ingredient',
                'joinTable'              => 'ingredients_recipes',
                'foreignKey'             => 'recipe_id',
                'associationForeignKey'  => 'ingredient_id',
                'unique'                 => 'keepExisting',
                'conditions'             => '',
                'fields'                 => '',
                'order'                  => '',
                'limit'                  => '',
                'offset'                 => '',
                'finderQuery'            => '',
                'deleteQuery'            => '',
                'insertQuery'            => ''
            )
    );
}

成分食谱.php

<?php
class IngredientRecipe extends AppModel {
    public $name = 'IngredientsRecipes';
    public $belongsTo = array('Ingredient', 'Recipe');
}

视图:

查看/成分食谱/添加.ctp

<?php echo $this->Form->create('IngredientRecipe'); ?>
    <?php echo $this->Form->input('Ingredient.ingredient', array('type' => 'text', 'label' => 'Ingredient')); ?>
    <?php echo $this->Form->input('Recipe.recipe', array('type' => 'text', 'label' => 'Recipe')); ?>
    <button type="submit">Save</button>
<?php echo $this->Form->end(); ?>

收费员:

成分配方控制器.php

<?php
class IngredientRecipeController extends AppController {
public function add() {
    if ($this->request->is('post')) {
     if(!empty($this->request->data)) {
       $ingredients_comma_separated = explode(',', $this->request->data['Ingredient']['ingredient']);
       $recipes_comma_separated = explode(',', $this->request->data['Recipe']['recipe']);
       $recipes = array();
         foreach($ingredients_comma_separated as $ingredient){
         $recipes['Ingredient']['ingredient'] = trim($ingredient);
         foreach($recipes_comma_separated as $recipe){
         $recipes['Recipe']['recipe'] = trim($recipe);
        if ($this->IngredientRecipe->saveAssociated($recipes, array('deep' => true, 'validate' => 'first'))) {
            $this->Session->setFlash('Saved.');
            }
          }
        }
      } 
    }
  }
}

MySQL 表:

CREATE TABLE IF NOT EXISTS `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ingredient` varchar(250) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ingredient` (`ingredient`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `ingredients_recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ingredient_id` int(11) NOT NULL,
  `recipe_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `recipe` varchar(250) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `recipe` (`recipe`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

我的问题:

我如何在食谱和成分字段中保留现有数据并继续将相关数据保存在ingredients_recipes字段中?

'unique' => 'keepExisting',不是为了这个。它的作用是将其他行的现有信息保留在连接表中,但它的行为仍然与'unique' => true相同。

看:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#ref-habtm-arrays

您需要做的是将其设置为 false。

由于配方和成分记录已经存在,您应该能够获得他们的 ID。然后在保存数据时,您只需提供 id 即可保存新关系,例如

dataArray = array(
    'recipe'=>array('id'=>$recipeId),
    'ingredient'=>array('id'=>$ingredientId)
);

这样,recipe表和ingredient表中的记录就不会被修改或复制。

如果表单中的输入是文本而不是下拉列表等选择,则可能需要在保存关系之前手动查找 id。

在配方和成分模型中都是唯一=假并从配方控制器做

$this->Recipe->saveAll($this->request->data)

我认为这会起作用