2012-08-04 123 views
1

我遇到了一個我試圖在cakePHP(在這裏找到cakephp is querying extra column and I can't figure out why)製作的投票系統的問題,但我想到了這一點,現在我又遇到了另一個問題。模型關聯與cakephp的問題

我正在製作一個投票系統,而我遇到的問題是隻有一個用戶可以在給定的帖子上投票。例如,如果用戶1對帖子1進行投票,然後用戶2對帖子1投票,則用戶2的投票將覆蓋用戶1的投票。

這裏是我的表

Votes 
id | user_id | vote 

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

我無法建立協會

  1. 用戶可以在很多帖子

  2. 投票後可以有很多選票,但每個用戶只有1個

這是我的用戶模型

public $hasMany = array(
    'Posts' => array('className' => 'Post'), 
    'Votes' => array('className' => 'Vote') 
    ); 

這是在我的職位模型

public $hasMany = array(//there can be multiple votes of the same id (references post table) 
    'Votes' => array('foreignKey' => 'id') 
    ); 

我沒有票控制器。這是通過PostsController.php上的投票功能完成的

回答

1
public $hasMany = array(//there can be multiple votes of the same id (references post table) 
    'Votes' => array('foreignKey' => 'id') 
    ); 

是錯誤的。它應該是:

public $hasMany = array(//there can be multiple votes of the same id (references post table) 
'Votes' => array('foreignKey' => 'post_id') 
); 

所以您必須在投票模型中添加post_id。

+0

您是否在數據庫中創建它? – 2012-08-04 20:45:21

+0

對不起,沒有看到之後的評論。我改變了它,但現在用戶可以在同一篇文章上多次投票。 – user1406951 2012-08-04 20:58:32

+0

是的。您現在必須在add方法中添加一些代碼來防止這種情況發生。 – 2012-08-04 21:04:01