Sequelize 关联查询合并数据字段

nodejs yekong 591℃

查询方式1

products.findAll({
            attributes: ['prdName', 'price'],
            include: [{
                model: user,
                as: 'u',
                attributes: ['userName']
            }],
            //raw:true
        }).then(result => {
            console.log(JSON.stringify(result))
        }).catch(err => {
            console.log(err)
        });

结果

[
            {
                "prdName": "ipad",
                "price": 4.99,
                "u": {"userName": "张三"}
            },
            {
                "prdName": "iphone",
                "price": 3.658,
                "u": {"userName": "张三"}
            },
            {
                "prdName": "联想笔记本",
                "price": 9.32,
                "u": {"userName": "李四"}
            }
        ]

查询方式2

products.findAll({
            attributes: ['prdName', 'price'],
            include: [{
                model: user,
                as: 'u',
                attributes: ['userName']
            }],
            raw:true
        }).then(result => {
            console.log(JSON.stringify(result))
        }).catch(err => {
            console.log(err)
        });

结果

[
            {
                "prdName":"ipad",
                "price":4.99,
                "u.userName":"张三"
            },
            {
                "prdName":"iphone",
                "price":3.658,
                "u.userName":"张三"
            },
            {
                "prdName":"联想笔记本",
                "price":9.32,
                "u.userName":"李四"
            }
        ]

查询方式3

products.findAll({
            attributes: [Sequelize.col('u.userName'),'prdName', 'price'],
            include: [{
                model: user,
                as: 'u',
                attributes: []
            }],
            raw:true
        }).then(result => {
            console.log(JSON.stringify(result))
        }).catch(err => {
            console.log(err)
        });
[
            {
                "userName":"张三",
                "prdName":"ipad",
                "price":4.99
            },
            {
                "userName":"张三",
                "prdName":"iphone",
                "price":3.658
            },
            {
                "userName":"李四",
                "prdName":"联想笔记本",
                "price":9.32
            }
        ]
喜欢 (0)