I currently have a table setup for the opinion (either 1 or 0) of a user on an article.
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;
I want to get a user’s “article score,” which is just how many other users have voted their article as good. The trick is that a user can have many articles. Is there a way to do this without returning all opinions on all articles for a user, then using a for loop to check for opinion==1?
In your Article model, add the following relation:
Then
$Article->scoreshould return that number for you.