代码仓库:https://github.com/changeclass/koa2-weibo
数据关联
1 2 3 4
| Blog.belongsTo(UserRelation, { foreignKey: 'userId', targetKey: 'followerId' })
|
此关系不会建立成功,因为此关系在数据库中已经被使用了,但是作为sequlize
是可以使用此关系的。
自己关注自己
创建完用户就应该自己关注自己,为了方便获取数据。
在创建用户时只需要调用addFollow
函数即可。但是为了在首页不显示自己。还需要在获取关注/粉丝列表时进行限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| const Sequelize = require('sequelize')
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 } }
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 } }
|