2009-01-07 40 views
3

嗨這是一個非常具體或非常通用的排隊 - 我不確定,而且我通常對Zend框架/ oo不熟悉。請耐心等待,如果這是一個愚蠢的Q ...在Zend模型中使用多個表並返回一個組合結果集

不管怎樣,我想創建一個模型,它確實是這樣的:

Read all the itmes from a table 'gifts' into a row set 

for each row in the table, read from a second table which shows how many have been bought, the append this as another "field" in the returned row 

return the row set, with the number bought included. 

最簡單的Zend例子似乎在只使用一個表模型,但我的閱讀似乎表明我應該在那裏完成大部分工作,而不是在控制器中。如果這是一個過於普遍的問題,那麼與2個表一起工作並返回數組的模型的任何示例都將非常棒!

感謝您的幫助提前!

+0

嗨布萊恩,TX響應。 Iit正是我想要做的,但是我無法獲得零件。$ select = $ this-> getAdapter() - > select() 零件。我知道這是試圖獲得與數據庫的連接,但我不能讓它工作,你能指出我解釋如何引用數據庫的東西嗎? – 2009-01-07 20:33:02

回答

1

我會建議在你的禮物模型類中創建一個函數,它返回你想要的東西。它可能看起來像這樣:

public function getGiftWithAdditionalField($giftId) { 
    $select = $this->getAdapter()->select() 
    ->from(array('g' => 'gifts')) 
    ->joinLeft(array('table2' => 't2'), 'g.gift_id = t2.gift_id', array('field' => 'field')) 
    ->where('g.gift_id = ?', $giftId); 
    return $this->getAdapter->fetchAll($select); 
} 

你可以檢查出Zend Framework Docs on Joins欲知更多信息。

+0

我打算鏈接到http://framework.zend.com/manual/en/zend.db.table.relationships.html,直到我重讀這個問題,並看到只需要額外的字段。 – 2009-01-07 17:43:32

2

我假設第二個表就像「gift_order」或其他東西。

在這種情況下,您需要通過外鍵指定「gift」和「gift_order」之間的表關係,並在表類中對其進行描述。

It will look like this 

    class GiftOrder extends Zend_Db_Table_Abstract 
    { 
    /** Table name */ 
    protected $_name = 'gif_order'; 
    protected $_referenceMap = array(
    "Fileset" =>array(
     "columns" => array("gifId"), 
     "refTableClass" => "Gift", 
     "refColumns" => array("id") 
    )); 
     ........................ 

You need to specify foreigh key constraint while create table with SQL 
     ALTER TABLE `gift_order` 
    ADD CONSTRAINT `order_to_gift` FOREIGN KEY (`giftId`) REFERENCES `gift` (`id`) ON DELETE CASCADE; 

如果這是你找,你可以在此鏈接link http://framework.zend.com/manual/en/zend.db.table.relationships.html

利用上述方案找到更多關於這一點,你就可以循環的禮物,並得到他們的訂單沒有任何複雜的SQL的

$ rowSetGifts = $ this-> findGifts();

while($rowSetGifts->next()){ 
    $gift = $rowSetGifts->current(); 
    $orders = $gift->findGiftOrder();//This is magick methods, this is the same $gift->findDependentRowset('GiftOrder'); 

//現在你可以用訂單東西 - 數($訂單),環它們或編輯

}

相關問題