-
用戶表(users)
id username 唯一標識,沒有登錄的可直接使用 _openid 用戶名 -
文章表(articles)
id title content 唯一標識 標題 內容 -
關聯表(relation)
index userId articleId 唯一索引 用戶 ID 文章 ID
用戶喜歡文章時,向 relation 添加一條數據,
用戶取消喜歡時,從 relation 刪除對應的數據。
需求
-
查詢文章列表,返回文章標題、喜歡人數、用戶是否喜歡
第一步:先查詢出文章列表 : select * from articles
- 第二步:遍歷文章列表,查詢關聯表得到用戶是否喜歡、喜歡人數
-
for (article : articles) { isLike = ( select * from relation where articleId = article.id && userId = 'userId' ) likeCount = ( select count(*) from relation where articleId = article.id ) article.isLike = isLike article.likeCount = likeCount } const db = cloud.database() const getArticles = async (event, context) => { const { userInfo: { openId } } = event return db.collection('articles').get().then(({ data }) => { let articles = [] for (let i = 0, length = data.length; i < length; ++i) { await Promise.all([ db.collection('relation').where({ articleId: data[i].id, }).count(), db.collection('relation').where({ articleId: data[i].id, userId: openId, }).count() ]).then(([likeCount, liked]) => { articles.push({ ...data[i], likeCount, liked: !!liked, }) }) } return { data: articles, message: 'success', } }).catch( err => { console.error(err.errMsg) return Promise.reject({ data: [], message: err.errMsg, }) }) } const db = cloud.database() const _ = db.command const getFavArticles = async (event, context) => { const { userInfo: { openId } } = event return db.collection('relation').where({ userId: openId, }).field({ articleId: true, }).get().then(({ data }) => { return db.collection('articles').where({ id: _in(data.map( item => item.articleId )), }).then(({ data: articles }) => { let result = [] for (let i = 0, length = articles.length; i < length; ++i) { await db.collection('relation').where({ articleId: articles[i].id, }).count().then(({ total }) => { result.push({ ...articles, likeCount: total, }) }) } return { data: result, message: 'success', } }) }).catch( err => { console.error(err) return Promise.reject({ data: [], message: err.errMsg, }) }) }