试图在cakephp中建立upvote系统

时间:2014-02-24 03:48:17

标签: php arrays cakephp

我正在尝试构建一个upvote system in cakephp,但我遇到了一些麻烦,最终导致了未识别的索引错误和数组到字符串的转换。

这是我在PostsController中的功能:

public function like ($id=null, $like=NULL) {
    if(!$id) {throw new NotFoundException(__('Invalid post'));
    }
    $post = $this -> Post-> findById($id);
    $like = $this->Like->find('all', array(
        'conditions' => array('username' =>
            array($this->Auth->user('username')))
    ));
    if(!$post) {throw new NotFoundException(__('Invalid post'));
    }
    $this -> set('post',$post);
    $this -> set('like', $like);
    if ($like['Like']['username'] == $post['Post']['username'] && $like['Like']['article_id'] == $post['Post']['id']){
        $this->redirect(array('action'=>'index'));
    }
    else{
        $this->Like->saveField('username', $this->Auth->user('username'));
        $this->Like->saveField('article_id', $post);
        $this->redirect(array('action'=>'index'));
    }

}    

在我的控制器顶部,我var $uses = array('Post','Like');所以我的PostsController知道也使用Like模型。现在我知道问题是什么,我只是不知道如何解决它。当我设置字段时,在数据库中设置用户名,但$post返回所有帖子的数组。我想要发生的是它只返回我当前发布的帖子。这就是我在我看来所做的事情:

   <?php echo $this->Html->link(
                        'Like',
                        array('action'=>'Like',$post['Post']['id']));
     ?>

这是与该观点相关的行动:

        public function view ($id=null) {
if(!$id) {throw new NotFoundException(__('Invalid post'));
}
$post = $this -> Post-> findById($id);
if(!$post) {
    throw new NotFoundException(__('Invalid post'));
}
$this -> set('post',$post);
}

如何让我的链接功能只返回我想要的当前帖子而不是所有帖子的数组?

编辑 - 忘记提及我在帖子控制器的第13行出现Undefined index: Like错误。

1 个答案:

答案 0 :(得分:2)

你有

$like = $this->Like->find('all', array(
    'conditions' => array('username' =>
        array($this->Auth->user('username')))
));

这将为数组提供更多项目,因此您无法使用$like['Like']。这就是你收到警告的原因。

您可以使用$like[0]['Like']

如果您需要浏览每个喜欢的内容,可以

foreach ($like as $currentLike) {
     if ($currentLike['Like']['username'] == $post['Post']['username'] ....
}

请详细说明您进行这些比较和重定向的原因,也许可以重构更多代码。