获取 SQL 个不同的数据书架模型

Get SQL distinct data Bookshelf Model

我正在尝试通过书架模型从 MySQL 数据库中获取不同的数据。

部门主管:

Department.distinct('departmentName').fetchAll().then((result) => {
            return res.send({
                status: '204',
                message: 'Data is Fetched',
                error: false,
                data: result
            })
        }

部门模型:

Bookshelf.model('Department' , {
    tableName:'departments',
    hasSecurePassword: true,
    hasTimestamps : ['created_at' , 'updated_at'],
    softDelete: true,
    hidden: ['deleted_at'],

    parse: function(response){
        if(response.allowUseOfMyContactInformation != null)
        response.allowUseOfMyContactInformation = !!+response.allowUseOfMyContactInformation;
        return response;
    }
})

有人请帮助我遇到错误"Department.distinct is not a function"

问题是您正在尝试对模型而不是 Department 模型的对象进行查询。

对您的部门控制器进行更改

首先,您需要在部门控制器中导入部门模型

       const Department = require('your Department model path');
       const department = new Department();
       department.distinct('departmentName').fetchAll().then((result) => {
        return res.send({
            status: '204',
            message: 'Data is Fetched',
            error: false,
            data: result
        })

希望对您有所帮助。如果您有任何问题,请告诉我。

经过漫长的google。我发现查询 groupBy 救了我的命:

dashboard_department = (req, res) => {
    try {
        Department.query({
            groupBy: 'departmentName'
        }).fetchAll().then((result) => {
            return res.send({
                status: '204',
                message: 'Data is Fetched',
                error: false,
                data: result
            })
        }).catch((error) => {
            return res.send({
                status: '404',
                message: 'Data is not fetched',
                error: true,
                data: {}
            })
        })

    } catch (e) {
        return res.send({
            status: '404',
            message: 'Internal Server Error',
            error: true,
            data: {}
        })
    }
}