2

I have two models, Contract and TimeEntry. The TimeEntry model has 'hours' as a column and references a Contract through it's 'contract_id' foreign key column. I'd like to return the "total hours" for a contract based on the related time entries, which seems simple enough. I thought that this code would work,

const TimeEntry = use('App/Models/TimeEntry')

class Contract extends Model {
  static get computed() {
    return ['totalHours']
  }
  ...
  getTotalHours({ id }) {
    return await TimeEntry
      .query()
      .where('contract_id', id)
      .sum('hours')
      .fetch()
  }
}

However, it errors on "Unexpected token" and says that TimeEntry is the unexpected token.

Nicholas Harder
  • 1,496
  • 10
  • 15

1 Answers1

0

You should not use fetch() with sum().just remove fetch() and query return sum of contract hours as array.

const TimeEntry = use('App/Models/TimeEntry')

class Contract extends Model {
  static get computed() {
    return ['totalHours']
  }
  ...
  getTotalHours({ id }) {
    return await TimeEntry
      .query()
      .where('contract_id', id)
      .sum('hours')
  }
}