2012-08-03 50 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

它包含投票(或評級)系統的邏輯,該系統可以與應用程序中的任何其他模型記錄相關聯。