从sequelize ORM格式化响应对象

时间:2018-11-18 00:39:25

标签: mysql sequelize.js

Product.findAll({
    attributes: ['id', 'product_name', 'product_price'],
    include: [{
            model: Shop,
            attributes: ['id', 'shop_name'],
            required: true
        },
        {
            model: LikedUsers,
            //get number of users liked for this product
            //get first 4 users as an array
            required: true
        },
        {
            model: Comment,
            //get number of comments for this product
        }]
    }).then(products => {
            res.send(products);
    }).catch(err => {
            res.status(422).send(err.errors);
    });
}

产品表

id,shopId,categoryId ....

likedUser Table

userId,productId,

评论表

userId,productId

这将给我一系列产品对象。我想以这种方式格式化响应对象:

{
    "id": 669,
    "product_name": "Summer Fashion Brand Sexy Women Short",
    "product_price": "150.00",
    "shops":{ 
        "id": 1,
        "sho_name": "some shop"
    },
    "num_likedUsers" 30,
    "liked_users": [
        {
           userid: i,
           username: 'someuser',
           profile: 'someImage'
        },
        {
           userid: i,
           username: 'someuser',
           profile: 'someImage'
        }
     ],
    "num_comments": "0"
},

0 个答案:

没有答案