目前我有一个页面,我通过俱乐部的ID检索了有关该俱乐部的信息。我现在有一个评论框,我想在其中检索有关该俱乐部的评论,在评论表中,我有club_id,参数"club_id"被传递到此页面。目前我正在从表格中检索所有评论,但我只想要该俱乐部的评论。在正确的方向上点会很棒!
控制器:
class ClubDescriptionController extends Zend_Controller_Action
{
public $auth = null;
public function init()
{
$this->auth=Zend_Auth::getInstance();
}
http://pastebin.com/m66Sg26x
protected function authoriseUser()
{
if (!$this->auth->hasIdentity()) {
$route = array('controller'=>'auth', 'action'=>'index');
$this->_helper->redirector->gotoRoute($route);
}
}
}
型:
class Application_Model_DbTable_Comments extends Zend_Db_Table_Abstract
{
protected $_name = 'comments';
public function getComment($id) {
$id = (int) $id;
$row = $this->fetchRow('id = ' . $id);
if (!$row) {
throw new Exception("Count not find row $id");
}
return $row->toArray();
}
public function addComment($comment, $club_id) {
$data = array(
'comment' => $comment,
'club_id' => $club_id,
'comment_date' => new Zend_Db_Expr('NOW()'),
);
$this->insert($data);
}
public function deleteComment($id) {
$this->delete('id =' . (int) $id);
}
}
观点:
<div id="view-comments">
<?php foreach($this->comments as $comments) : ?>
<p id="individual-comment">
<?php echo $this->escape($comments->comment);?> -
<i><?php echo $this->escape($comments->comment_date);?></i>
</p>
<?php endforeach; ?>
</div>
我意识到我将不得不在我的模型中使用 getComment(); 函数并通过 id 查询它,但我对究竟如何...
谢谢
自从我使用Db_Table以来已经有一段时间了,但我认为您想创建一个选择对象,它允许您构建一个查询,该查询将选择具有正确club_id的评论:
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$this->view->comments = $comments->fetchAll($select);
您可能希望按日期对注释进行排序,如果是这样,您可以通过向 Select 中添加 Order 子句来执行此操作:
$select->order('comment_date ASC');
看看Zend_Db_Table_Select的文档,其中有很多例子: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.fetch-all
在控制器中,您正在调用
$this->view->comments = $comments->fetchAll();
它应该是
$this->view->comments = $comments->getComment($this->_request->getParam('club_id'));
其中 id 变量将从 URL 获取。
这是工作控制器:
public function indexAction() {
//authorisation
$this->authoriseUser();
//to get the paramter club_id to query for specific club information
$id = (int) $this->_request->getParam('club_id', 0);
//submit a comment
$form = new Application_Form_Comment();
$form->submit->setLabel('Comment');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$comment = new Application_Model_DbTable_Comments();
$comment->addComment($formData['comment'], $id);
} else {
$form->populate($formData);
}
}
//initialise table
$clubs = new Application_Model_DbTable_Clubs();
$clubs = $clubs->getClub($id);
$this->view->clubs = $clubs;
//to get the comments for the club
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$select->order('comment_date ASC');
$this->view->comments = $comments->fetchAll($select);
}