koa2使用查询当前用户的收藏列表

nodejs yekong

api

// 收藏列表
collectionApi.linPost(
    'collection',
    '/list',
    user.permission('收藏'),
    loginRequired,
    async ctx => {
        const uid = ctx.currentUser.dataValues.id; // 获取用户id
        var data=ctx.request.body;
        const Collection = await CollectionDto.getCollections({uid: uid,...data});
        ctx.json(Collection);
    }
);
async getCollections(data) {
        console.log(data)
        const collections = await Collection.findAll({
            where: {
                uid: data.uid
            },
            limit: parseInt(data.pageSize),
            offset: parseInt(data.pageSize) * (parseInt(data.pageNum) - 1),
            include: [{ // include关键字表示关联查询
                model: Book, // 指定关联的model
                as: 'book', // 由于前面建立映射关系时为class表起了别名,那么这里也要与前面保持一致,否则会报错
                attributes: [], // 这里的attributes属性表示查询class表的name和rank字段,其中对name字段起了别名className
            }],
            // attributes: ['pid', 'id'],
            attributes: [Sequelize.col('book.title'),'uid','pid', 'id'],
            raw: true,
        });
        const count = await Collection.count({
            where: {
                uid: data.uid
            },
        });
        return {
            list: collections,
            total: count
        };
    }

这里使用了 Sequelize 关联查询合并数据字段第三种查询方式将返回的数据合并到一块
接口返回数据

{
    "list": [
        {
            "title": "321",
            "uid": "2",
            "pid": "1",
            "id": 25
        },
        {
            "title": "123",
            "uid": "2",
            "pid": "2",
            "id": 24
        }
    ],
    "total": 2
}
喜欢