2011-05-13 46 views
0

因此,我正在努力學習Kohana,當涉及到他們的ORM模塊時,我遇到了相當多的障礙。 當試圖設置一對多ORM對象時,我能夠更新/插入來自父模型的信息,但它不會允許我關聯(插入/更新)任何新的子項。

爲了清楚起見,這裏是我的數據庫結構...

recipes 
--id 
--recipe 
--directions 
--servings 

ingredients 
--id 
--recipe_id 
--amount 
--serving 

items 
--id 
--item 

......我的模特...

class Model_Recipe extends ORM 
{ 
    protected $_has_many = array('ingredient' => array()); 
} 

class Model_Ingredient extends ORM 
{ 
    protected $_belongs_to = array('recipe' => array()); 
    protected $_has_one = array('item' => array()); 
} 

class Model_Item extends ORM 
{ 
    protected $_belongs_to = array('ingredient' => array()); 
} 

......和我的控制器.. 。

class Controller_Recipe extends Controller 
{ 
    function action_save_form() 
    { 
     $recipe = ORM::factory('recipe', 1); 

     $recipe->ingredient->recipe_id = 1; 
     $recipe->ingredient->amount = 1; 
     $recipe->ingredient->measurement_type = 'tablespoon'; 
     $recipe->ingredient->save(); 

     $recipe->ingredient->item->item = 'butter'; 
     $recipe->ingredient->item->ingredient_id = $recipe->ingredient->id; 
     $recipe->ingredient->item->save(); 
    } 

} 

我毫不猶豫地承認這是由於我的無能,但我已經通過源代碼瞭解了docs/wiki/read(ing),並且一直無法找到任何接近的東西。感謝任何人可能有的幫助/想法

編輯:重新閱讀後,它可能不是很清楚。我正在嘗試做的是更新$ recipe對象,然後更新/添加配料,以及它們的一對一子對象(項目),如下所示:

+0

如果有幫助,我使用Kohana 3.1.2 – JoeCortopassi 2011-05-13 05:10:27

回答

3

奧斯汀指出,有許多關係應該是按照慣例複數。

你缺少的另一件事是填充與數據有很多關係;有在做你想要的方式,而是沒有任何意義:

function action_save_form() 
{ 
    $recipe = ORM::factory('recipe', 1); 

    // Create an ingredient and attach it to the recipe (one-to-many) 
    $ingredient = ORM::factory('ingredient')->values(array(
     'amount'   => 1, 
     'measurement_type' => 'tablespoon', 
     'recipe'   => $recipe, // sets the fk 
    )); 

    $ingredient->create(); 

    // Update all ingredients? 
    foreach ($recipe->ingredients->find_all() as $ingredient) 
    { 
     $ingredient->amount = 2; 
     $ingredient->update(); 
    } 

    // Create an item and attach to the recipe (one-to-one) 
    $item = ORM::factory('item')->values(array(
     'item'   => 'butter', 
     'ingredient' => $ingredient, 
    )); 

    $item->create(); 

    // Update the recipes' item after it's been created 
    $ingredient->item->item = 'chocolate'; 
    $ingredient->item->update(); 
} 

注意:這個例子沒有趕上ORM_Validation_Exceptions,應在爲了得到驗證錯誤進行。

+1

只需注意 - 您的代碼適用於Kohana v3.1.x(使用'save()'方法而不是'create()'和' update()'for 3.0.x) – biakaveron 2011-05-13 06:26:24

+0

@biakaveron謝謝你的明確表示,他已經指定他使用3.1.2 – Kemo 2011-05-13 07:56:29

3

對於$ _has_many,您應該複數化。

相反的:

protected $_has_many = array('ingredient' => array());

嘗試:

protected $_has_many = array('ingredients' => array());

+0

如果我沒有弄錯,那Kohana-2,而不是Kohana-3(我正在使用) – JoeCortopassi 2011-05-13 05:08:00

+0

不能 - KO3仍然使用Inflector類在適當的地方使用單數/複數形式,使得代碼閱讀更像你自然語言中所說的方式。就我個人而言,我非常欣賞這個功能。請參閱http://kohanaframework.org/3.1/guide/orm/relationships#hasmany – Austin 2011-05-13 05:18:47