CakePHP博客教程的评论系统

时间:2010-06-03 01:03:25

标签: cakephp

我正在通过为每个帖子添加评论来构建博客引擎的CakePHP教程。我可以通过选择框选择应附加的帖子来添加评论。我希望能够点击帖子中的“添加评论”链接,并以编程方式与帖子建立关联。我不确定如何将post_id传递给comments_controller中的add方法。我的add方法的主体是自动生成的脚手架代码。是否像在add方法中添加$ postId参数一样简单,并将其写入我的评论模型中的post_id?这感觉不对,因为当我的提交按钮点击我的评论添加视图时,我希望调用add。

谢谢大家。

编辑 - 添加了我目前正在使用的代码。它只是我的comments_controller中的add方法。

function add($postid = null) {             
    if(!empty($this->data) {
         $this->Comment->create();                          
         $this->Comment->post_id = $postid;
         if ($this->Comment->save($this->data)) {
            $this->Session->setFlash(__('The Comment has been saved', true));
            $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('The Comment could not be saved. Please, 
                                          try again.', true));
         }
    }   
    $this->set('post_id', $postid);     
    print_r($postid);
}

2 个答案:

答案 0 :(得分:3)

function add($postid = null) {             
    if(!empty($this->data) {
         $this->Comment->create();                          
         $this->data['Comment']['post_id'] = $postid; // see how it needs to be?
         ...then save the data...

答案 1 :(得分:0)

在博客文章底部创建您的链接,

<?php echo $html->link('Add Comment', array('controller'=>'Comments','action'=>'add',$post->id)) ?>

然后,您可以在评论控制器的添加方法中

function add($postid){
  $this->data->Comment->post_id = $postid;
  $this->data->Save();
}

与此类似,你会说的很好。然后你的网址会example.com/comments/add/3仔细查看代码,因为这是早上的第一件事,我们的牛奶用完了,所以我没有咖啡! ;)

相关问题