0

我目前有一个表格设置用于用户对文章的意见(1 或 0)。

CREATE TABLE IF NOT EXISTS `opinion_article` 
(
`id`                INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`uid`               INT UNSIGNED NOT NULL, /* user with an opinion on the article */
`aid`               INT UNSIGNED NOT NULL, /* article ID */
`opinion`           BOOL NOT NULL, /* opinion on the article, 1 = good, 0 = bad */
FOREIGN KEY (`uid`) REFERENCES `user`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (`aid`) REFERENCES `article`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE (`uid`, `aid`)
) ENGINE=InnoDB;

我想获得一个用户的“文章分数”,这就是有多少其他用户将他们的文章投票为好。诀窍是用户可以拥有许多文章。有没有办法在不为用户返回所有文章的所有意见的情况下执行此操作,然后使用 for 循环检查意见==1?

4

2 回答 2

1

在您的文章模型中,添加以下关系:

'score'=>array(self::STAT, 'OpinionArticle', 'aid', 'condition'=>'opinion=1')

然后$Article->score应该为您返回该号码。

于 2012-12-29T03:35:05.867 回答
0

随着威廉留下的答案,我来到了这个很好的解决方案。基本上我只是在我的“opinion_article”表中为作者的 ID 添加了一个额外的字段。

CREATE TABLE IF NOT EXISTS `opinion_article` 
(
`id`                INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`uid`               INT UNSIGNED NOT NULL,
`aid`               INT UNSIGNED NOT NULL, /* article ID */
`author_id`         INT UNSIGNED NOT NULL, /* the author of the article's ID */
`opinion`           BOOL NOT NULL, /* opinion on the article, 1 = good, 0 = bad */
FOREIGN KEY (`uid`) REFERENCES `user`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (`aid`) REFERENCES `article`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`author_id`) REFERENCES `user`(`id`) ON UPDATE CASCADE ON DELETE CASCADE,
UNIQUE (`uid`, `aid`)
) ENGINE=InnoDB;

然后,在我的用户模型中,我添加了这一行:

        'articleScore'=>array(self::STAT, 'OpinionArticle', 'author_id', 'condition'=>'opinion=1'),

然后我可以通过调用 $user->articleScore 来获得文章分数

于 2012-12-31T02:30:39.860 回答