laravel selectRaw for MONTH(created_at)无法运行测试

zbdgwd5y  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(162)

我在Laravel 10用户模型中有一个函数,它每月计算计算的平均值,并在视图上显示。对于我的应用程序来说,它工作得很好,但是当我用这个视图的assertStatus运行测试时,会显示一个错误。

  1. public function numCalculationsAvgMonth(): string
  2. {
  3. $data = NumberOfCalculations::where('user_id', $this->id)
  4. ->selectRaw('
  5. count(id) as data,
  6. YEAR(created_at) as year,
  7. MONTH(created_at) as month
  8. ')
  9. ->groupby('year', 'month')
  10. ->get()
  11. ->avg('data');
  12. return decimals($data, 2);
  13. }

我的测试结果是下一个:

  1. SQLSTATE[HY000]: General error: 1 no such function: YEAR (Connection: sqlite, SQL: select
  2. count(id) as data,
  3. YEAR(created_at) as year,
  4. MONTH(created_at) as month
  5. from "number_of_calculations" where "user_id" = 1 group by "year", "month")

我需要在我的TestCase中使用一个trait?

sshcrbum

sshcrbum1#

错误消息“无此功能:YEAR”表示测试环境不支持selectRaw()方法中使用的YEAR()函数。一种解决方案是使用strftime()函数,SQLite支持该函数,可用于从日期中提取年和月。
下面是numCalculationsAvgMonth()函数的一个可能版本,它使用strftime()并返回一个浮点数而不是字符串:

  1. public function numCalculationsAvgMonth(): float
  2. {
  3. $data = NumberOfCalculations::where('user_id', $this->id)
  4. ->selectRaw('count(id) as data, strftime("%Y", created_at) as year, strftime("%m", created_at) as month')
  5. ->groupBy('year', 'month')
  6. ->get()
  7. ->avg('data');
  8. return round($data, 2);
  9. }

相关问题