模型与cakephp的关联问题

时间:2012-08-04 20:07:52

标签: php mysql cakephp database-relations

我在使用cakePHP(在这里cakephp is querying extra column and I can't figure out why找到)的投票系统遇到了麻烦,但我想出来了,现在我又遇到了另一个问题。

我正在制作一个投票系统,而我遇到的问题是只有一个用户可以对某个帖子投票。例如,如果用户1在帖子1上投票,然后用户2在帖子1上投票,则用户2的投票将覆盖用户1的投票。

这是我的表格

Votes
id |   user_id   | vote

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

我在设置关联时遇到了麻烦

  1. 用户可以对很多帖子进行投票

  2. 帖子可以有很多票,但每个用户只有1票

  3. 这是我的用户模型

    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 个答案:

答案 0 :(得分: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。

相关问题