我通过这样做来解决它:
在控制器中
public function projectsAction() {
$projects = $this->getProjectsTable()->fetchAll();
$i = 0;
foreach ($projects as $project) {
$imgs = array();
$pros[] = $project;
$images = $this->getProjectImagesTable()->fetchAll($project->id);
foreach ($images as $img) {
$imgs[] = $img;
$pros[$i]->images = $imgs;
}
$i++;
}
return new ViewModel(array(
'projects' => $pros
));
}
在项目中
<?php
//IN MODEL FOLDER
namespace Application\Model;
class Projects
{
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name = (isset($data['name'])) ? $data['name'] : null;
$this->country = (isset($data['country'])) ? $data['country'] : null;
}
}
?>
在项目表中
<?php
//IN MODEL FOLDER
namespace Application\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
class ProjectsTable extends AbstractTableGateway {
protected $table = 'projects';
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Projects());
$this->initialize();
}
public function fetchAll() {
$select = new Select();
$select->from('projects', array('projects.*'));
//echo $select->getSqlString();
$resultSet = $this->selectWith($select);
$resultSet->buffer();
return $resultSet;
}
}
在项目图像中
<?php
//IN MODEL FOLDER
namespace Application\Model;
class ProjectImages {
public $id, $project_id, $image_name, $date;
public function exchangeArray($data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->project_id = (isset($data['project_id'])) ? $data['project_id'] : null;
$this->image_path = (isset($data['image_path'])) ? $data['image_path'] : null;
$this->date = (isset($data['date'])) ? $data['date'] : null;
}
}
在 ProjectImagesTable 中
<?php
namespace Application\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
class ProjectImagesTable extends AbstractTableGateway {
protected $table = 'project_images';
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new ProjectImages());
$this->initialize();
}
public function fetchAll($id) {
$select = new Select();
$select->from('project_images', array())
->where(array('project_id' => $id));
//echo $select->getSqlString();
$resultSet = $this->selectWith($select);
$resultSet->buffer();
return $resultSet;
}
}