繁体   English   中英

Cakephp与模型关联的麻烦

[英]Model association trouble with cakephp

我在尝试使用cakePHP创建的投票系统遇到了麻烦(在这里发现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上的表决功能完成的

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')
);

因此,您必须在Vote模型中添加post_id。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM