【问题标题】:Use Query Builder inside computed property in Adonis JS在 Adonis JS 的计算属性中使用查询生成器
【发布时间】:2019-06-14 13:39:23
【问题描述】:

我有两个模型,Contract 和 TimeEntry。 TimeEntry 模型将“小时”作为列,并通过它的“contract_id”外键列引用合同。我想根据相关时间条目返回合同的“总小时数”,这似乎很简单。我认为这段代码可以工作,

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()
  }
}

但是,它在“意外令牌”上出错,并说 TimeEntry 是意外令牌。

【问题讨论】:

    标签: javascript knex.js adonis.js


    【解决方案1】:

    您不应该将 fetch() 与 sum() 一起使用。只需删除 fetch() 并将合约小时数的返回总和查询为数组。

    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')
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2016-03-17
      • 2018-11-09
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多