CakePHP 2.1:HABTM saveAssociated并保留存在的数据

时间:2012-05-06 19:12:32

标签: php cakephp cakephp-2.1

我对saveAssociated和存在条目有一点问题:(

型号:

为ingredient.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'            => ''
            )
    );
 }

Recipe.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'            => ''
            )
    );
}

IngredientRecipe.php

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

查看:

查看/ IngredientsRecipes / add.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(); ?>

Contollers:

IngredientRecipeController.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 ;

我的问题:

如何在配方中保留存在的数据&amp;成分字段并继续在ingredients_recipes字段中保存相关数据?

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

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

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

这样,recipeingredient表中的记录将不会被修改或重复。

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

答案 2 :(得分:0)

在配方和成分模型中使unique = false 从食谱控制器做

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

我认为这会起作用