2012-08-03 124 views
0

编辑在表中存在价值 - 我修正原来的错误,但现在我还有一个如何检查是否使用CakePHP

当我点击“给予好评”我得到的消息“的投票无效保存“消息,这意味着无论出于何种原因,它都不能正确查询(否则会看到没有保存的记录)。另外,我收到一个错误,提示“未定义索引”,但我不确定它指的是什么。

这里是我的表

Votes 
id | user_id | vote 

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

这是一个链接,给予好评的发现帖子/ index.ctp

<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

试试这个

添加在你的控制器

<?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.')); 
      } 
     } 
    } 

} 
+0

你可以得到user_id查询字符串或会话 – 2012-08-03 03:59:00

+0

我更新了我上面的代码。你可以看看它,我仍然有错误吗? – user1406951 2012-08-04 00:01:11

+0

你有使用投票我认为你的模型名称应该是Vote $ this-> Post->投票和你在Vote.id中使用的条件,它应该是Vote.post_id并显示我的你的帖子和投票数据库表strostcher – 2012-08-04 03:26:51

1

你会发现这个插件,你的情况有所帮助:

https://github.com/CakeDC/ratings

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