2011-12-02 18 views
0

據我所知,CakePHP沒有內置的處理記錄重新排序的機制。所以,我使用Ordered Behavior,就像我所知道的,它是CakePHP中重新排序的事實行爲。到目前爲止,它運行良好,因爲我將它添加到各種模型,但是,我有一個我不知道如何處理的情況。有多個外鍵的CakePHP有序行爲

我的模型層次如下。

Section > Heading > Category > Item

然而,項目可以直接連接到部分:

Section > Item

的項目模型的表有兩個category_id和定義section_id,但只有一個是真正用於任何給定的記錄。

當您設置模型的$actsAs時,有序行爲有兩個參數設置。下面是一個對我的頭球型號:

var $actsAs = array('Ordered' => array('field' => 'order','foreign_key' => 'section_id')); 

我應該怎樣定義$actsAs成員的項目模型,其中有兩個外鍵section_idcategory_id,以確保排序/順序正確維護?

+0

要獲得答案,您可能需要添加一個您正在提供的輸入和您希望輸出的示例。我不能完全理解你正在努力創造的效果。 –

+0

我不確定輸入是什麼意思。我擁有的是一個模型,它可以是兩個模型中的一個模型的子模型,並且有序行爲可以維護基於外鍵的給定模型組的排序,因此附加到類別X的項目獨立於附加到類別Y的項目,A部分和B部分。這有助於澄清? – theraccoonbear

+1

這將需要大量的改變。我建議爲「部分項目」設置「隱形」類別。 –

回答

0

我還沒有對此進行廣泛的測試,但是在第一次嘗試時,這似乎是一種解決方法,它可以讓我動態管理排序。在我的ItemsController我有以下操作:

function moveup($id = null) { 
     if (!$id) { 
      $this->Session->setFlash(__('Invalid id for Item', true)); 
     } else { 
      $item = $this->Item->read(null, $id); 

      if ($item['Item']['section_id'] != 0) { 
       $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'section_id')); 
      } else { 
       $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'category_id')); 
      } 

      if ($this->Item->moveup($id)) { 
       $this->Session->setFlash(__('Item moved up', true)); 
      } else { 
       $this->Session->setFlash(__('Item move failed', true)); 
      } 
     } 

     $this->redirect($this->referer()); 
    } 

    function movedown($id = null) { 
     if (!$id) { 
      $this->Session->setFlash(__('Invalid id for Item', true)); 
     } else { 
      $item = $this->Item->read(null, $id); 

      if ($item['Item']['section_id'] != 0) { 
       $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'section_id')); 
      } else { 
       $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'category_id')); 
      } 

      if ($this->Item->movedown($id)) { 
       $this->Session->setFlash(__('Item moved down', true)); 
      } else { 
       $this->Session->setFlash(__('Item move failed', true)); 
      } 
     } 

     $this->redirect($this->referer()); 
    } 

我的模型不設置通過$actsAs成員的有序行爲(因而foreign_key)。相反,在任何訂單操作之前,我都會在運行時確定父項類型並附加相應的行爲,並帶有適當的foreign_key

+0

我想我看到的最大問題是它違反了MVC模式,將應該是模型邏輯的東西放入控制器。任何人都可以建議如何在模型中構建它? – theraccoonbear