Yii - 计数和关系

时间:2012-12-29 03:25:14

标签: yii relational-database

我目前有一个表格设置用于文章上用户的意见(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?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

随着Willem留下的答案,我找到了这个很好的解决方案。基本上我只是在我的观点中添加了一个额外的字段'作者姓名表。

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

来获得文章分数