十、从零模拟新浪微博-首页
代码仓库:https://github.com/changeclass/koa2-weibo
数据关联
Blog.belongsTo(UserRelation, {
foreignKey: 'userId',
targetKey: 'followerId'
})此关系不会建立成功,因为此关系在数据库中已经被使用了,但是作为
sequlize是可以使用此关系的。
自己关注自己
创建完用户就应该自己关注自己,为了方便获取数据。
在创建用户时只需要调用addFollow函数即可。但是为了在首页不显示自己。还需要在获取关注/粉丝列表时进行限制
const Sequelize = require('sequelize')
/**
* @author: 小康
* @url: https://xiaokang.me
* @param {*} userId
* @description: 获取关注人列表
*/
async function getFollowerByUser(userId) {
const result = await UserRelation.findAndCountAll({
order: [['id', 'desc']],
include: [
{
model: User,
attributes: ['id', 'userName', 'nickName', 'picture']
}
],
where: {
userId,
userId: {
[Sequelize.Op.ne]: userId
}
}
})
let userList = result.rows.map((row) => row.dataValues)
userList = userList.map((item) => {
let user = item.user
user = user.dataValues
user = formatUser(user)
return user
})
return {
count: result.count,
userList
}
}
/**
* @author: 小康
* @url: https://xiaokang.me
* @param {number} followerId 被关注人的ID
* @description: 获取关注该用户的用户列表
*/
async function getUsersByFollower(followerId) {
const result = await User.findAndCountAll({
attributes: ['id', 'userName', 'nickName', 'picture'],
order: [['id', 'desc']],
include: [
{
model: UserRelation,
where: {
followerId,
userId: {
[Sequelize.Op.ne]: followerId
}
}
}
]
})
// 格式化
let userList = result.rows.map((row) => row.dataValues)
userList = formatUser(userList)
return { count: result.count, userList }
} 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs









