2009-01-07 59 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'); 

//现在你可以用订单东西 - 数($订单),环它们或编辑

}

相关问题