2012-08-04 158 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