Using multiple tables in a Zend model and returning a combined result set

Hi This is either very specific or very general code - I'm not sure, and I'm new to Zend framework / oo in general. Please be patient if this is stupid Q ...

Anyway, I want to create a model that does something like:

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.

Most simple Zend examples seem to use only one table in a model, but my reading seems to suggest that I should do most of the work there, and not in the controller. If this is too general a question, any example model that works with 2 tables and returns an array would be great!

Thanks for your help in advance!

+3
source share
2 answers

, - "gift_order" - .

"" "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),

}

+2

, , . , :

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 .

+1

All Articles