sequelize常见API使用

时间:2019-02-11
本文章向大家介绍sequelize常见API使用,主要包括sequelize常见API使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

     1.对查询出来的属性起别名

// 第一种:根据id查询一条记录 
const favors = await UserModel.findOne({
    attributes: [['user_favorites', 'userFavors']], //将user_favorites属性重命名为userFavors
    where: {
        id: `${id}`
    }
}).catch(err => {
    getLogger().error("xxx occur error=", err);
});
// 第二种:只对查询出来的几个属性中的个别起别名
const list = await UserModel.findAll({
    where: {
        id: `${id}`
    },
    attributes: ['id', ['user_favorites', 'userFavors'], ['create_time', 'createTime'], 'update_time']
});

    2.如果要查询的字段属性非常多,而你又不需要某些属性,那么就可以使用$notIn

// 排除不需要的字段
const excludes = ['gender', 'status', 'updateTime', 'createTime'];
let list = await UserModel.findAll({
    where: {
        name: {
            $notIn: excludes
        }
    }
});

    3.如果你只需要查询某几个字段,那么可以使用$in

// 只获取需要的字段
const includes = ['name', 'age', 'tel', 'address'];
await UserModel.findAll({
    where: {
        name: {
            $in: includes
        }
    }
})

    4.通过主键来查询一条记录

await UserModel.findByPk(id).then(......

    5.查询条件中有多个属性筛选项,并且其中一个属性等于给定的值中任何一个都可以,就要对这个属性用到$or操作符

await UserModel.findOne({
    where: {
        country: "china",
        userFavors: {
            $or: ['book', 'film'] //查询国家是China,并且userFavors等于book或者film的人
        },
        status: 1
    }
});

    6.前台分页组件有时会需要查询全部记录数,这时可以直接使用count

let counts = await UserModel.count({
    where: {
        status: 1
    }
});