2012-11-15 41 views
0

我建立使用Kohana的3.2和Kohana的ORM一個應用程序。Kohana的ORM門店數量在許多一對多的關係

應用程序具有系統。系統包含組件。一個系統可能包含多個組件,但也可能包含多個相同類型的組件。例如。 System_A可能有10 Component_Y和3 Component_Z

所以,而不只是有兩個belongs_to的在我的透視表我也想將計字段。

如果我只是用一種具有一對多,通過我將無法訪問計數。如果沒有ORM,我只需將count加入到SQL中的組件中,因爲count對於System + Component組合是唯一的,所以當我訪問特定系統上下文中的對象時,可以訪問該組件的計數。

如何最好地去了解這個在Kohana的ORM?

回答

0

我解決這部分是這樣的:

protected $_has_many = array(
     'omvormer' => array(
      'model' => 'omvormer', 
      'through' => 'systeemomvormer' 
     ), 
     'systeemomvormer' => array(
      'model' => 'systeemomvormer', 
     ) 
    ); 

我加樞TABEL systeemomvormer分頭systeem

我現在可以這樣做:

$so = ORM::factory("systeemomvormer"); 
$so->where('systeem_id', '=', $systeem_id); 
$so->where('omvormer_id', '=', $omvormer_id); 
$result = $so->find(); 
$result->aantal = $omvormer_count; 

但它確實仍然只是部分解決方案,因爲我無法update()結果。 Kohana說結果沒有加載。然而,這超出了這個問題的範圍,我會爲此提出一個新問題。

這也是有幫助的: http://forum.kohanaframework.org/discussion/7247/kohana-3-orm-save-for-update-a-many-to-many/p1

0

要存儲不僅僅是兩個鍵結表的詳細數據,你需要創建一個模型它。

所以,

system _has_many system_component 
component _has_many system_component 
system_component _belongs_to component 
system_component _belongs_to system 

但是,您可能不需要將計,如果你做這種方式。相反,你可以做到以下幾點:

$system->components->count_all(); 

然後,對其進行訪問:

foreach($system->components->find_all() as $component) 
    echo $component->component->name;