簡體   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