【问题标题】:aggregation on loopback mysql query环回 mysql 查询上的聚合
【发布时间】:2019-11-10 22:05:34
【问题描述】:

我想知道如何对我的环回查询进行聚合我使用 MySQL 作为数据库我在我的数据库中有这样的记录 - { 'app_name': 'chrome', 'duration' : 10000 }, { 'app_name': 'WhatsApp', 'duration' : 25000 } and so on 请注意,持续时间以毫秒为单位。我正在使用 Angular 7 作为前端,我想进行环回查询来总结我所有记录的持续时间,现在我正在做一个类似的查询 -

Apps.find({}).toPromise()
    .then(apps => {
        let result = apps.reduce((app, total) = {
            total += app.duration;
            return total
        }, 0)
        console.log(result);
    })
    .catch(err => {
        console.log(err);
     })

但是,使用这种方法,我可以获得持续时间的总和,但如果我有数百万条记录,那么它不是一个可扩展的解决方案,例如从数百万条记录中迭代然后对持续时间求和。 我想知道 MySQL 的环回查询中是否存在聚合。 我想要一个类似的查询 -

Apps.find({
      aggregation: {
       sum: 'duration'
     }
    }).toPromise()
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
     })

类似的东西。

【问题讨论】:

    标签: mysql loopback


    【解决方案1】:

    LoopBack 还不支持聚合。我的建议是编写一个自定义控制器方法,该方法将执行自定义 SQL 查询来聚合结果。

    // in your controller
    export class MyController {
      constructor(
        @repository(AppRepository) protected appRepo: AppRepository
      ) {}
    
      // default CRUD methods scaffolded by lb4
    
      // custom method
      @get('/apps/durations')
      getDurations() {
        return this.appRepo.getAggregatedDurations();
      }
    }
    
    // in your AppRepository
    export class AppRepository extends DefaultCrudRepository<
      App,
      typeof App.prototype.id,
      AppRelations
    > {
      constructor(
        @inject('datasources.db') dataSource: juggler.DataSource,
        // ...
      ) {
        super(App, dataSource);
        // ...
      }
    
      // add a new method
      async getAggregatedDurations(): Promise<number> {
        // A mock-up SQL query, you may need to tweak it
        const result = await this.execute('SELECT SUM(duration) as total_duration FROM Apps');
        // I am not entirely sure what's the shape of result object,
        // you have to find out yourself how to access "total_duration" field 
        return result[0].total_duration;
      }
    }
    

    另请参阅execute 方法的 API 文档:https://loopback.io/doc/en/lb4/apidocs.repository.executablerepository.execute.html 和 LoopBack 3.x 文档:https://loopback.io/doc/en/lb3/Executing-native-SQL.html

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2021-02-03
      • 2010-10-23
      • 2010-10-29
      • 2017-04-04
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 2020-05-31
      相关资源
      最近更新 更多