0

编辑 - 我修复了原来的错误,但现在我还有一个

当我单击“Upvote”时,我收到消息“投票无法保存”消息,这意味着无论出于何种原因,它都没有正确查询(否则它会看到没有保存记录)。另外,我收到一条错误消息“未定义索引”,但我不确定它指的是什么。

这是我的桌子

Votes
id |  user_id | vote

Posts
id |  title | body | created | modified | user_id | vote_total

这是posts/index.ctp上的upvote链接之一

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

所以,这是在 postscontroller.php 中找到的投票函数

public function vote($id=null){

$this->Post->Votes->recursive = 0;

$this->Post->id = $id;
$user = $this->Auth->User();
$userid = $user['id'];
$conditions = array('votes.id' => $id, 'votes.user_id' => $userid, 'votes.vote' => '1');

$data = $this->Post->Votes->find('All' , array('conditions'=>$conditions));

if (isset($data) && !empty($data)) {
    echo '<p>User have already give a vote!</p>';
} else {

    if($this->Post->Votes->validates()){
        if ($this->Post->Votes->save($this->request->data)) {
                $this->Session->setFlash(__('The vote has been saved'));
        } else {
                $this->Session->setFlash(__('The vote could not be saved. Please, try again.'));
        }
    }   
}
}

这种关系可以在我的 Post.php 模型中找到。

public $hasMany = array(
    'Votes' => array(
        'foreignKey' => 'id'
        )
    );

这种关系可以在 User.php 模型中找到

public $hasMany = array(
    'Posts' => array(
        'className'  => 'Post'
        )
    );
4

2 回答 2

2

尝试这个

添加你的控制器

<?php

public function vote($id=null){

    $this->layout = 'votes_layout';
    $this->Vote->recursive = 0;

    $user = $this->Auth->User();
    $userid = $user['id'];
    $conditions = array('Vote.post_id' => $id, 'Vote.user_id' => $userid);


    $data = $this->Vote->find('All' , arrar('conditions'=>$conditions));

    if (isset($data) && !empty($data) {
        echo '<p>User have already give a vote!</p>';
    } else {

        if($this->Vote->validates()){

            if ($this->Vote->save($this->request->data)) {
                    $this->Session->setFlash(__('The vote has been saved'));
                    $this->redirect(array('action' => 'vote'));
            } else {
                    $this->Session->setFlash(__('The vote could not be saved. Please, try again.'));
            }
        }   
    }

}
于 2012-08-03T03:51:00.300 回答
1

您可能会发现此插件对您的情况很有帮助:

https://github.com/CakeDC/ratings

它包含投票(或评级)系统的逻辑,该系统可以与您应用程序中的任何其他模型记录相关联。

于 2012-08-03T07:58:13.107 回答