2009-09-21 35 views
4

我是zend的新手。我被要求重新開發曾經用普通PHP編寫的網站,並將其放入zend框架中。zend與select的關係

我在數據庫關係方面遇到了很多麻煩,我似乎無法讓我的腦袋定義和查詢關係。

我想找到一個類別。從那個類別中,我希望能夠找到與它關聯的所有CategoryInfo,並且能夠查詢/排序/限制該數據集。

這是我的模特。

Categorys.php

<?php 
    class Default_Model_Categorys extends Zend_Db_Table_Abstract 
    { 
     protected $_name = 'Categorys'; 
     protected $_primary = 'id'; 

     protected $_dependentTables = array('Default_Model_CategoryInfo'); 
} 
?> 

CategoryInfo.php

<?php 
class Default_Model_CategoryInfo extends Zend_Db_Table_Abstract 
{ 
    protected $_name = 'Category_Info'; 
    protected $_primary = 'id'; 

    protected $_referenceMap = array(
     'Categorys' => array(
      'columns' => array('cat_id'), 
      'refTableClass' => 'Default_Model_Categorys', 
      'refColumns' => array('id') 
     ) 
    ); 
} 
?> 

CategoryController.php

<?php 
    class CategorysController extends Zend_Controller_Action 
    { 
     public function indexAction() 
     { 
     /* 
      this should redirect to all games 
     */ 
      return $this->_forward("index", "games"); 
     } 

     public function categoryAction() 
     { 
      /* 
      shows a specific category 
      */ 
      $id = (int) $this->_request->getParam('id'); 
      $category = new Default_Model_Categorys(); 
      $this->view->category = $category->fetchRow(
       $category->select()->where('id = ?', $id) 
     ); 

      $categoryInfo = $this->view->category->findDependentRowset('Default_Model_CategoryInfo'); 

     } 
    } 

首先......我我做錯了什麼?

其次......我該如何去查詢依賴行集?

回答

2

首先,如果你正在尋找它的主鍵的範疇,它更簡單使用find()方法:

$id = (int) $this->_request->getParam('id'); 
$category = new Default_Model_Categorys(); 
$this->view->category = $category->find($id)->current(); 

其次,限制或排序依賴Category_Info行,你可以使用一個Zend_Db_Table_Select對象作爲findDependentRowset()的可選參數。以下是一個示例:

$select = $category->select()->where("info_type = 'PRICE'") 
          ->order("info_date") 
          ->limit(3); 
$categoryInfo = $this->view->category->findDependentRowset(
    'Default_Model_CategoryInfo', null, $select); 

注意,您可以使用任何表格對象來創建該選擇對象。由於對於選擇「FROM」條款將被findDependentRowset()方法進行設置,你只需要添加其他條款,然後通過它在

PS:你並不需要聲明$_dependentTables可言,除非你打算通過PHP代碼使用級聯更新或級聯刪除。我強烈建議這樣做 - 讓RDBMS處理這些級聯操作要高效得多。

同樣,如果您的數據庫表實際聲明瞭主鍵約束,則您不應該聲明$_primaryZend_Db_Table_Abstract知道如何檢查元數據以獲取主鍵列。

+0

比爾你英雄。我謝謝你!問題解決了。 – sfusion 2009-09-22 08:27:29

+0

很高興幫助!我編輯了上面的代碼,將調用添加到'current()',因爲'find()'總是返回一個行集合,而不是一行。 – 2009-09-22 08:35:24

0

一切看起來都正確。您不查詢從屬行集。這是一個查詢本身,它返回一個結果集。基本上它所做的就是拉取與$ _referenceMap定義的當前行相關的所有記錄。一旦執行findDependentRowset(),您可以對結果進行foreach,這會給您示例Zend_Db_Table_Row。從那裏你可以根據需要顯示相關數據。

我個人並不使用Zend_Db關係。只需製作第二個模型方法來查詢我需要的內容就容易多了。此外,Zend_Db關係不支持,其中子句,因此只是進行第二個查詢比關係更靈活。