3

嗨,这是一个非常具体或非常通用的问题 - 我不确定,而且我通常是 Zend 框架/oo 的新手。如果这是一个愚蠢的Q,请耐心等待...

无论如何,我想创建一个执行以下操作的模型:

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 个表并返回数组的模型示例都会很棒!

提前感谢您的帮助!

4

2 回答 2

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;

如果这是您正在寻找的东西,您可以在此链接链接 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');

//现在你可以对订单做一些事情 - count($orders),循环它们或编辑

}

于 2009-01-23T20:28:46.423 回答
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了解更多信息。

于 2009-01-07T16:54:10.157 回答