2011-05-12 53 views
0

我有一個Doctrine 1.2項目,我正在重構爲了使用具有多個根的原則beahaviour NestedSet的表的樹結構。Doctrine 1.2來自祖先的NestedSet屬性和關係繼承

我需要的是從祖先到後代的繼承(不是OO的常識),後代中子孫繼承自己的屬性失蹤的最近祖先的屬性。關係也會發生同樣的事情。

讓我用一個例子解釋:

Category: 
    actAs: 
    NestedSet: 
     hasManyRoots: true 
     rootColumnName: root_id 
    columns: 
    name: string(50) 
    another_property: string(50) 
    active: boolean 
Tag: 
    columns: 
    value: string(50) 
CategoryTag: 
    columns: 
    category_id: integer 
    tag_id: integer 

我想執行的是:

  • 檢索,如果一類是積極的,這意味着覈實,如果所有的 祖先是活動
  • 如果給定類別缺少another_property,則從 繼承其最近的祖先
  • 檢索給定類別的標籤;如果標籤丟失,檢索他們從最近的祖先

你會爲了最大限度地速度和靈活性,建議作爲最好的方法是什麼 ?

回答

0

那麼,這是非常簡單的。剛剛獲得與關係,你需要這樣的樹:

class ModelTable extends Doctrine_Table 
    { 
     /** 
     * Gets tree element in one query 
     */ 
     public function getModelTree() 
     { 

     $q = $this->createQuery('g') 
      ->leftJoin('g.Tags t') 
      ->orderBy('g.root_id') 
      ->addOrderBy('g.lft') 
      ->where('g.root_id NOT NULL') 
; 
     return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY); 
     } 
    } 

然後,你可以使它像這樣:

<?php function echoNode($tree, $parent=null) { ?> 
    <ul> 
    <?php foreach ($tree as $node): ?> 
    <li data-property='<?php echo false != $node['property'] ? $node['property'] : $parent['property'] ?>'> 
     <?php echo $node['name'] ?> 
     <?php if (count($node['__children']) > 0): ?> 
     <?php echo echoNode($node['__children'], $node) ?> 
     <?php endif; ?> 
    </li> 
    <?php endforeach; ?>  
    </ul> 
<?php } ?> 

<?php echo echoNode($tree) ?> 

注意,你怎麼可以從父節點獲取「財產」,如果它缺席。解決這個問題的另一種方法是使用Doctrine_Core :: HYDRATE_RECORD_HIERARCHY。這允許在循環時用於在$節點上調用方法。您可以創建一個Model :: getClosestProperty()方法,例如,從最接近的父級獲取該屬性。但是,這不如陣列水合。