Php 在Zend模型中使用多个表并返回组合结果集

Php 在Zend模型中使用多个表并返回组合结果集,php,zend-framework,Php,Zend Framework,您好,这是一个非常具体或非常通用的问题-我不确定,我对Zend框架/oo一般来说是新手。如果这是一个愚蠢的问题,请耐心等待 无论如何,我想创建一个模型,它可以执行以下操作: 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

您好,这是一个非常具体或非常通用的问题-我不确定,我对Zend框架/oo一般来说是新手。如果这是一个愚蠢的问题,请耐心等待

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

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.
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示例似乎只在模型中使用一个表,但我的阅读似乎建议我应该在那里做大部分工作,而不是在控制器中。如果这是一个过于泛化的问题,那么任何一个使用2个表并返回一个数组的模型示例都将非常好


提前谢谢你的帮助

我建议在gifts模型类中创建一个函数,返回您想要的内容。它可能看起来像:

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.
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);
}

您可以查看以了解更多信息。

我假设第二张表类似于“礼品订单”之类的东西

在这种情况下,您需要通过外键指定“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;
如果这是你要找的东西,你可以在这个链接上找到更多

使用这种解决方案,您将能够循环礼物并获得他们的订单,而无需任何复杂的SQL

$rowSetGifts=$this->findGifts()

//现在,您可以对订单进行操作—计数($orders)、循环或编辑订单


}

我本来打算链接到,直到我重新阅读问题,发现只需要额外的字段。嗨,Brian,德克萨斯州,请回答。这正是我想要做的,但是我无法得到$select=$this->getAdapter()->select()部分。我知道这是试图获得连接到数据库,但我只是不能让它工作,你能告诉我一些解释如何引用数据库?