我想在 View 上列出类似的内容
Number Commands | Date of commands | Description (text from table article)
我只有
Number Commands | Date of commands | Description (id from table Bc)
我有两个表:BC(作为命令),其中包含列:id_commands、id_article、id_user、number_commands、date_commands,... 和表 Article ,其中包含以下列:id_article、name_article、description_article、...
根据本教程,How to extend the ZF2 skeleton application - entities with foreign keys
这是我的代码:
在 Bc\Model\Bc.php
class Bc implements BcInterface
{
...
public function setArticle(ArticleInterface $bc_article)
{
$this->article = $bc_article;
}
public function getArticle()
{
return $this->bc_article;
}
}
在 Bc\Mapper\BcHydrator.php
namespace Bc\Mapper;
class BcHydrator // extends Zend\Stdlib\Hydrator\ClassMethods
{
public function extract($object)
{
return array(
'bc_id' => $object->getBc_id(),
'article_designation' => $object->getA_designation(),
'article_reference' => $object->getA_reference()
);
}
}
在 Bc\Mapper\ZendDbSqlMapper.php
...
public function findAllWithArticle()
{
$sql = new Sql($this->dbAdapter);
$select = $sql -> select()
-> from( array('a'=>'s_article'))
-> join( array('bc' => 's_bc'),
'bc.bc_id_article = a.a_id');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
if ($result instanceof ResultInterface && $result->isQueryResult()) {
$resultSet = new HydratingResultSet($this->hydrator, $this->bcPrototype);
\Zend\Debug\Debug::dump($result);die();
//return $resultSet->initialize($result);
}
return array();
}
在我的 Controller 上
...
public function detailAction()
{
$id = $this->params()->fromRoute('id');
try {
//$bc = $this->bcService->findBc($id);
$bc = $this->bcService->findAllBcsWithArticle($id);
$articleDesignation = $bc->getArticle()->getA_designation();
} catch (\InvalidArgumentException $ex) {
return $this->redirect()->toRoute('bc');
}
return new ViewModel(array(
'bc' => $bc,
'article' => $articleDesignation
));
}
当我有权访问我的 View 时,出现此错误:
Fatal error: Call to undefined method Zend\Db\ResultSet\HydratingResultSet::getArticle()
有人知道我做错了什么吗?
最佳答案
最后我为那些想知道的人找到了解决方案。 我没有使用保湿剂,但我得到了我想要的结果。
在我的类 Bc (Bc\Model\Bc.php) 上添加一个 protected 变量 $description 并设置 setter 和 getter。
在我的 Mapper (Bc\Mapper\ZendDbSqlMapper.php) 上,我添加了一个函数 findContent ($id),并用作 sql 请求:
$sql = new Sql($this->dbAdapter); $select = $sql -> select() -> from( array('bc'=>'bc')) -> join( array('a' => 'article'), 'bc.bc_id_article = a.id', array( 'description' => 'description', )); $select->where(array('bc_id = ?' => $id));
- 在我的服务上 (Bc\Service\BcService.php)
public function findBcsContent($id) { return $this->bcMapper->findContent($id); }
- 在我的 Controller 上
public function indexAction() { return new ViewModel(array( 'bcs'=> $this->bcService->findAllBcsContent() )); }
- 在我看来,我可以使用
$this->escapeHtml($bc->getDesignation());
就这些了
关于php - 如何使用具有外键的 Hydrator 并在 ZF2 中的 View 上显示两个实体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941550/