【问题标题】:CakePHP: complicated join modelCakePHP:复杂的连接模型
【发布时间】:2012-08-19 13:09:56
【问题描述】:

以下场景:

Recipe hasMany RecipeItem
RecipeItem belongsTo Recipe, Ingredient

Ingredient 可以与 hasMany RecipeItem 关联,但我不需要这种关系。)

所以基本上,一个没有连接表的单面HABTM,因为我的连接元素(RecipeItem)需要有一个额外的属性:count。

这篇文章:http://book.cakephp.org/1.3/view/1650/hasMany-through-The-Join-Model 描述了如何一次创建/保存全部或完全分离。我想要的是创建分离的一侧(成分)和关联的另一侧(食谱)。创建新配方时,您可以选择多种成分。

你会怎么做? 谢谢。

【问题讨论】:

标签: php cakephp join has-and-belongs-to-many


【解决方案1】:

老实说,我认为您应该尝试简化您的架构。这听起来不必要的复杂。为什么您需要同时记录 RecipeItem 成分?它们看起来应该是一样的。

您可以在连接表中创建额外的字段,这样就不需要额外的关系。我认为你应该能够只使用配方 HABTM 成分并完成。

另外,为了让 cake 的自动魔法正常工作,我往往无法正确格式化表单数据。对我来说,更容易格式化我想要手动保存的连接表记录,然后用连接表模型显式保存它们(在清除现有记录之后)。类似:

$toSave = array();
$this->loadModel('RecipesIngredients');
foreach($this->data['Ingredient'] as $ingredient) {
    $toSave[] = array(
        'recipe_id'=>$this->data['Recipe']['id'],
        'ingredient_id'=>$ingredient['id'],
        'count'=>$ingredient['count']
    );
}
$this->RecipesIngredients->deleteAll(array('recipe_id'=>$this->data['Recipe']['id']);
$this->RecipesIngredients->saveAll($toSave);

【讨论】:

  • 在连接表中添加一个额外的属性字段是我首先做的(这本来是完美的),但是 HABTM 的默认表单输入是多选,我如何将属性计数关联到多选中的每个选定项目,因为它们是无序的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多