【问题标题】:Model association trouble with cakephpcakephp的模型关联问题
【发布时间】:2012-08-02 10:36:58
【问题描述】:

我在尝试用 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 个投票

这是在我的用户模型中

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 上的投票功能完成的

【问题讨论】:

    标签: php mysql cakephp database-relations


    【解决方案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。

    【讨论】:

    • 你是在数据库中创建的吗?
    • 抱歉,之后没有看到该评论。我更改了它,但现在用户可以在同一个帖子上多次投票。
    • 是的。您现在必须在 add 方法中添加一些代码来防止这种情况发生。
    • 我需要在 posts 方法中添加一些东西来防止这种情况发生吗?我只有一个 Posts 和 Users 方法。投票只是我 PostsController 中的一个函数
    • 您必须在投票功能中检查这是用户第一次投票。
    猜你喜欢
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多