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

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

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

public function numCalculationsAvgMonth(): string
    {
        $data = NumberOfCalculations::where('user_id', $this->id)
            ->selectRaw('
                count(id) as data,
                YEAR(created_at) as year,
                MONTH(created_at) as month
            ')
            ->groupby('year', 'month')
            ->get()
            ->avg('data');

        return decimals($data, 2);
    }

我的测试结果是下一个:

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

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

sshcrbum

sshcrbum1#

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

public function numCalculationsAvgMonth(): float
{
    $data = NumberOfCalculations::where('user_id', $this->id)
        ->selectRaw('count(id) as data, strftime("%Y", created_at) as year, strftime("%m", created_at) as month')
        ->groupBy('year', 'month')
        ->get()
        ->avg('data');

    return round($data, 2);
}

相关问题