如何使用cakephp检查表中是否存在值

时间:2012-08-03 02:27:55

标签: php mysql cakephp

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

当我点击“Upvote”时,我收到消息“投票无法保存”消息,这意味着无论出于何种原因,它都没有正确查询(否则会发现没有保存记录)。另外,我收到一条错误,上面写着“Undefined index”,但我不确定它是指什么。

这是我的表格

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'
        )
    );

2 个答案:

答案 0 :(得分: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.'));
            }
        }   
    }

}

答案 1 :(得分:1)

您可能会发现此插件对您的案例很有用:

https://github.com/CakeDC/ratings

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