2012-08-19 102 views
0

以下情形:CakePHP的:复杂的连接模型

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描述如何创建/保存一次或完全分开。我想要的是创造一方(成分)分开,另一方(食谱)与协会一起。创建新配方时,您可以选择多种配料。

你会如何做到这一点? 谢谢。

+0

尝试http://cakeapp.com – powtac 2012-08-19 13:27:48

回答

0

老实说,我认为你应该尝试简化你的模式。这听起来不必要的复杂。为什么您需要RecipeItem 的配料?他们似乎应该是同一件事。

您可以在连接表中创建其他字段,因此您不需要额外的关系。我认为你应该能够使用食谱HABTM配料并完成。

此外,我倾向于格式化我的表单数据正确的蛋糕的automagic工作。对我来说,格式化我想手动保存的连接表记录并使用连接表模型(在清除现有记录之后)显式保存它们会更容易。是这样的:

$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); 
+0

增加一个额外的属性字段连接表要弄清楚它是什么,我做了第一次(这将是完美的),但默认表单输入对于HABTM是一个多重选择,我如何将属性计数与多选中的每个选定项相关联,因为它们是无序的? – 2012-08-19 14:36:23