CREATE TABLE post_likes (
post_id INT NOT NULL,
user_id INT NOT NULL,
likes BOOLEAN NOT NULL,
FOREIGN KEY (post_id) REFERENCES posts(id),
FOREIGN KEY (user_id) REFERENCES users(id),
PRIMARY KEY (user_id, post_id)
)
+-------+---------+---------+
| likes | post_id | user_id |
+-------+---------+---------+
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 0 | 2 | 1 |
| 0 | 2 | 2 |
+-------+---------+---------+
我使用NodeJS和EJS作为模板语言。现在我将表post_likes传递给我的EJS。并尝试做一个for循环。基本上在表1 =真或喜欢,0 =假或不喜欢。所以我有一个计数器,如果它像我一样反对++ else counter--。但它看起来很糟糕。它也因某种原因不起作用什么是更好的方法。
我尝试了什么 - 我排除了不需要的代码的其他部分。我删除了关闭括号的ejs并打开以使其更具可读性。
<% var counter = 0 %>
for(var i = posts.length-1; i >= 0; i--) {
if(posts[i].post_likes.length > 0) {
for(var j = 0; j < posts[i].post_likes.length; j++) {
if(posts[i].post_likes[j].likes == true) {
counter = counter + 1 %>
}
else if(posts[i].post_likes[j].likes == false) {
counter = counter - 1
}
}
}
}
<h1><%= counter %></h1>
答案 0 :(得分:0)
你可以做这样的事情来获得喜欢和不喜欢的帖子。
var posts = [{
post_likes: [{
likes: true
}]
}, {
post_likes: [{
likes: true
}]
}, {
post_likes: [{
likes: false
}]
}, {
post_likes: [{
likes: true
}]
}];
var likedPosts = 0;
var unlikedPosts = 0;
posts.forEach(function(post) {
likedPosts += post.post_likes.filter(function(v) {
return v.likes === true;
}).length;
unlikedPosts += post.post_likes.filter(function(v) {
return v.likes === false;
}).length;
});
console.log('Liked posts: ' + likedPosts);
console.log('Unliked posts: ' + unlikedPosts);