2013-11-18 4 views
3

Я использую zend framework 2.2 на xampp. У меня есть модуль «Альбом».выборка данных из разных таблиц базы данных

структура каталогов:

enter image description here

моя таблица базы данных: 'альбом'

модуль кода: код

<?php 

namespace Album; 

use Album\Model\Album; 
use Album\Model\AlbumTable; 
use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 

class Module { 

    public function getAutoloaderConfig() { 
     return array(
      'Zend\Loader\ClassMapAutoloader' => array(
       __DIR__ . '/autoload_classmap.php', 
      ), 
      'Zend\Loader\StandardAutoloader' => array(
       'namespaces' => array(
        __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, 
       ), 
      ), 
     ); 
    } 

    public function getConfig() { 
     return include __DIR__ . '/config/module.config.php'; 
    } 

    public function getServiceConfig() { 
     return array(
      'factories' => array(
       'Album\Model\AlbumTable' => function($sm) { 
        $tableGateway = $sm->get('AlbumTableGateway'); 
        $table = new AlbumTable($tableGateway); 
        return $table; 
       }, 
       'AlbumTableGateway' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $resultSetPrototype = new ResultSet(); 
        $resultSetPrototype->setArrayObjectPrototype(new Album()); 
        return new TableGateway('album', $dbAdapter, null, $resultSetPrototype); 
       }, 
      ), 
     ); 
    } 

} 

контроллер:

<?php 

namespace Album\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 
use Album\Model\Album; 
use Album\Form\AlbumForm; 

class AlbumController extends AbstractActionController { 

    protected $albumTable; 

    public function getAlbumTable() { 
     if (!$this->albumTable) { 
      $sm = $this->getServiceLocator(); 
      $this->albumTable = $sm->get('Album\Model\AlbumTable'); 
     } 
     return $this->albumTable; 
    } 

    public function indexAction() { 
     return new ViewModel(array(
        'albums' => $this->getAlbumTable()->fetchAll(), 
        'active' => 'albumindex', 
       )); 
} 
} 

код модели:

<?php 

namespace Album\Model; 

use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 
use Zend\Db\Sql\Select; 
use Zend\Paginator\Adapter\DbSelect; 
use Zend\Paginator\Paginator; 

class AlbumTable 
{ 
    protected $tableGateway; 

    public function __construct(TableGateway $tableGateway) 
    { 
     $this->tableGateway = $tableGateway; 
    } 

    public function fetchAll($paginated=false) 
    { 
      $resultSet =$this->tableGateway->select(function (Select $select) { 
      $select->order('title ASC'); 
      }); 
      return $resultSet; 
    } 
} 

вид Код:

<?php 
// module/Album/view/album/album/index.phtml: 

$title = 'My albums'; 
$this->headTitle($title); 
?> 
<h1><?php echo $this->escapeHtml($title); ?></h1> 
<p> 
    <a href="<?php echo $this->url('album', array('action'=>'add'));?>">Add new album</a> 
</p> 

<table class="table"> 
<tr> 
    <th>Title</th> 
    <th>Artist</th> 
    <th>&nbsp;</th> 
</tr> 
<?php foreach ($albums as $album) : ?> 
<tr> 
    <td><?php echo $this->escapeHtml($album->title);?></td> 
    <td><?php echo $this->escapeHtml($album->artist);?></td> 
    <td> 
     <a href="<?php echo $this->url('album', 
      array('action'=>'edit', 'id' => $album->id));?>">Edit</a> 
     <a href="<?php echo $this->url('album', 
      array('action'=>'delete', 'id' => $album->id));?>">Delete</a> 
    </td> 
</tr> 
<?php endforeach; ?> 
</table> 

я получить выход как на рисунке ниже. enter image description here

Теперь я хочу получать данные из разных таблиц ('abm'), в то время как таблица 'album' все еще будет объявлена ​​в коде модуля.

return new TableGateway('album', $dbAdapter, null, $resultSetPrototype); 

(и пусть мои обе таблицы данных имеют ту же страницу просмотра structure.so и контроллер будет то же самое.) так, что я должен сделать для этого? как я могу использовать TableGateway() в коде модели для разных таблиц данных?

-thanks.

Edit:

я сделал следующее,

Модуль:

<?php 

namespace Album; 

use Album\Model\Album; 
use Album\Model\AlbumTable; 
**use Album\Model\AbmTable;** 
use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 

class Module { 

    public function getAutoloaderConfig() { 
     return array(
      'Zend\Loader\ClassMapAutoloader' => array(
       __DIR__ . '/autoload_classmap.php', 
      ), 
      'Zend\Loader\StandardAutoloader' => array(
       'namespaces' => array(
        __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, 
       ), 
      ), 
     ); 
    } 

    public function getConfig() { 
     return include __DIR__ . '/config/module.config.php'; 
    } 

    public function getServiceConfig() { 
     return array(
      'factories' => array(
       'Album\Model\AlbumTable' => function($sm) { 
        $tableGateway = $sm->get('AlbumTableGateway'); 
        $table = new AlbumTable($tableGateway); 
        return $table; 
       }, 
       'AlbumTableGateway' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $resultSetPrototype = new ResultSet(); 
        $resultSetPrototype->setArrayObjectPrototype(new Album()); 
        return new TableGateway('album', $dbAdapter, null, $resultSetPrototype); 
       }, 
       **'Album\Model\AbmTable' => function($sm) { 
        $tableGateway = $sm->get('AbmTableGateway'); 
        $table = new AbmTable($tableGateway); 
        return $table; 
       },       
       'AbmTableGateway' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $resultSetPrototype = new ResultSet(); 
        $resultSetPrototype->setArrayObjectPrototype(new Album()); 
        return new TableGateway('abm', $dbAdapter, null, $resultSetPrototype); 
       },**       
      ), 
     ); 
    } 

} 

Контроллер:

<?php 

namespace Album\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 
use Album\Model\Album; 
use Album\Form\AlbumForm; 

class AlbumController extends AbstractActionController { 

    protected $albumTable;protected $abmTable; 

    public function getAlbumTable() { 
     if (!$this->albumTable) { 
      $sm = $this->getServiceLocator(); 
      $this->albumTable = $sm->get('Album\Model\AlbumTable'); 
     } 
     return $this->albumTable; 
    } 

    **public function getAbmTable() { 
     if (!$this->abmTable) { 
      $sm = $this->getServiceLocator(); 
      $this->abmTable = $sm->get('Album\Model\AbmTable'); 
     } 
     return $this->abmTable; 
    }**  

    public function indexAction() { 
     return new ViewModel(array(
        'albums' => $this->getAlbumTable()->fetchAll(), 
        **'abms' => $this->getAbmTable()->fetchAll(),** 
       )); 
    } 
} 

модель (новая модель страницы: 'AbmTable.php'):

<?php 

namespace Album\Model; 

use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 
use Zend\Db\Sql\Select; 
use Zend\Paginator\Adapter\DbSelect; 
use Zend\Paginator\Paginator; 

class AbmTable 
{ 
    protected $tableGateway; 

    public function __construct(TableGateway $tableGateway) 
    { 
     $this->tableGateway = $tableGateway; 
    } 

    public function fetchAll($paginated=false) 
    { 
      $result =$this->tableGateway->select(function (Select $select) { 
      $select->order('title ASC'); 
      }); 
      return $result; 
    } 
} 

тогда я получил '$ АВМ' в странице просмотра с данными таблицы 'АБМ'.

Update:

выбирающий различные таблицы с той же модели.

Модуль:

namespace Album; 

use Album\Model\AlbumTable; 
use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 

class Module { 

    public function getAutoloaderConfig() { 
     return array(
      'Zend\Loader\ClassMapAutoloader' => array(
       __DIR__ . '/autoload_classmap.php', 
      ), 
      'Zend\Loader\StandardAutoloader' => array(
       'namespaces' => array(
        __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, 
       ), 
      ), 
     ); 
    } 

    public function getConfig() { 
     return include __DIR__ . '/config/module.config.php'; 
    } 

    public function getServiceConfig() { 
     return array(
      'factories' => array(
// 'album' table-------------------------------------     
       'Album\Model\AlbumTable\dbtable=album' => function($sm) { 
        $tableGateway = $sm->get('AlbumTableGateway'); 
        $table = new AlbumTable($tableGateway); 
        return $table; 
       }, 
       'AlbumTableGateway' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $resultSetPrototype = new ResultSet(); 
        $resultSetPrototype->setArrayObjectPrototype(new Album()); 
        return new TableGateway('album', $dbAdapter, null, $resultSetPrototype); 
       }, 
// 'abm' table-------------------------------------       
       'Album\Model\AlbumTable\dbtable=abm' => function($sm) { 
        $tableGateway = $sm->get('AbmTableGateway'); 
        $table = new AlbumTable($tableGateway); 
        return $table; 
       },       
       'AbmTableGateway' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $resultSetPrototype = new ResultSet(); 
        $resultSetPrototype->setArrayObjectPrototype(new Album()); 
        return new TableGateway('abm', $dbAdapter, null, $resultSetPrototype); 
       }, 
      ), 
     ); 
    } 
} 

Контроллер:

namespace Album\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 

class AlbumController extends AbstractActionController { 

    protected $albumTable; 
    protected $abmTable; 

    public function getAlbumTable() { 
     if (!$this->albumTable) { 
      $sm = $this->getServiceLocator(); 
      $this->albumTable = $sm->get('Album\Model\AlbumTable\dbtable=album'); 
     } 
     return $this->albumTable; 
    } 

    public function getAbmTable() { 
     if (!$this->abmTable) { 
      $sm = $this->getServiceLocator(); 
      $this->abmTable = $sm->get('Album\Model\AlbumTable\dbtable=abm'); 
     } 
     return $this->abmTable; 
    }  

    public function indexAction() { 
     return new ViewModel(array(
        'albums' => $this->getAlbumTable()->fetchAll(), 
        'abms' => $this->getAbmTable()->fetchAll(), 
       )); 
    } 
} 

Модель:

namespace Album\Model; 

use Zend\Db\ResultSet\ResultSet; 
use Zend\Db\TableGateway\TableGateway; 
use Zend\Db\Sql\Select; 

class AlbumTable 
{ 
    protected $tableGateway; 

    public function __construct(TableGateway $tableGateway) 
    { 
     $this->tableGateway = $tableGateway; 
    } 

    public function fetchAll($paginated=false) 
    { 
      $result =$this->tableGateway->select(function (Select $select) { 
      $select->order('title ASC'); 
      }); 
      return $result; 
    } 
} 

ответ

1

Если я правильно понимаю у вам просто нужно сделать еще один TableGateway для другой таблицы abm и создать для него класс сущности, тогда вы можете получить обе таблицы и показать их в поле зрения.

+0

Где я должен это делать? в модуле или на странице модели? – user1844626

+1

вы должны сделать почти то же самое, что и с Ablum в приложении zutorial zend, но теперь с помощью «abm», затем в вашем контроллере вы должны получить свой AbmTableGateway с fetchAll в нем (например), чтобы получить то, что вы хотите от «abm», Таблица. Сделайте это в mod.php вашей модели, вы можете сделать еще одну модель со всем этим, если хотите, и считаете, что вам нужно отделить «abm» от логики «альбом». – kilop

+0

см. Мое редактирование. Новые коды находятся между знаками **. теперь его работа. Это именно то, что вы просили меня сделать? Но могу ли я сделать это на той же странице модели, а не создавать новую страницу модели для новой таблицы? – user1844626

Смежные вопросы