phpzend-framework2zend-dbzend-db-tabletablegateway

Zend:Fetching Data from Multiple tables


Please find my code below

module.php

public function getServiceConfig()
{
return array(
'factories' => array(
'Shopping\Model\ShopTable' =>  function($sm) {
    $tableGateway = $sm->get('ShopTableGateway');
    $table = new ShopCategoriesTable($tableGateway);
    return $table;
},
'ShopTableGateway' => function ($sm) {
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new ShopCategories());
    return new TableGateway('shop_goods', $dbAdapter, null, $resultSetPrototype);
},
),
);
}

shoppingcontroller.php

public function getShopTable()
{
        if (!$this->shopTable) 
        {
            $sm = $this->getServiceLocator();
            $this->shopTable = $sm->get('Shopping\Model\ShopTable');
        }
        return $this->shopTable;
}

As you can see on my first code shop_categories is my database table from which iam fetching data ,above code works fine.But now i need to fetch data from an other table named as shop_goods how do i configure module.php?


Solution

  • Try this :

    module.php

    <?php
        public function getServiceConfig()
        {
            return array(
                'factories' => array(
                    'Application\Model\ShopgoodsTable' =>  function($sm) {
                        $tableGateway = $sm->get('ShopgoodsTableGateway');
                        $table = new ShopgoodsTable($tableGateway);
                        return $table;
                    },
                    'ShopgoodsTableGateway' => function ($sm) {
                        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                        $resultSetPrototype = new ResultSet();
                        $resultSetPrototype->setArrayObjectPrototype(new Shopgoods());
                        return new TableGateway('shops_goods', $dbAdapter, null, $resultSetPrototype);
                    },
                ),
            );
        }
    

    And in your controller

    public function getShopgoodsTable()
    {
            if (!$this->shopGoodsTable) 
            {
                $sm = $this->getServiceLocator();
                $this->shopGoodsTable= $sm->get('Shopping\Model\ShopgoodsTable');
            }
            return $this->shopGoodsTable;
    }