如何定义指标以在请求中使用其他日期时间字段?

问题描述 投票:0回答:1

阅读 https://nova.laravel.com/docs/metrics/defining-metrics.html#value-metrics 文档 在 Laravel 10 / nova 4.27 应用程序中,我使用命令添加了指标:

php artisan nova:value OrdersCompleted

我只需要计算completed_by_manager_at字段的已完成订单。

订单型号有范围:

public function scopeOnlyCompleted($query)
{
    return $query->where($this->table . '.status', OrderStatusEnum::COMPLETED);
}

并在 app/Nova/Metrics/OrdersCompleted.php 中我修改了:

class OrdersCompleted extends Value
{
    /**
     * Calculate the value of the metric.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @return mixed
     */
    public function calculate(NovaRequest $request)
    {
        return $this->count($request, Order::onlyCompleted());
    }

检查 sql 我看到:

   SELECT count(`orders`.`id`)     AS aggregate
    FROM `orders`
    WHERE `orders`.`status` = 'O'     AND `orders`.`created_at` between '2024-01-01 00:00:00'     AND '2024-10-28 05:38:01'

在文档中,我没有找到如何代替created_at字段来使用completed_by_manager_at字段?

修改#1:

在订单模式中我添加了范围:

public function scopeGetCompletedByManagerAtBetweenDates($query, datetime $date1 = null, datetime $date2 = null): Builder
{
    if( !empty($date1) and !empty($date2)) { // THESE conditions are false
        \Log::info('$date1::');
        \Log::info($date1);
        $query->whereBetween($this->table . '.completed_by_manager_at', [$date1, $date2]);
    }
    return $query;
}

并在我的 OrdersCompleted metrix 类中使用此范围:

public function calculate(NovaRequest $request)
{
    \Log::info( '-1 OrdersCompleted $request->all()::' . print_r( $request->all(), true  ) );

    return $this->count($request, Order::onlyCompleted()->getCompletedByManagerAtBetweenDates());
}

在日志中我看到 $request->all() 有值:

[timezone] => UTC
[range] => 30

如何计算 getCompletedByManagerAtBetweenDates 方法的范围天数?

eloquent laravel-nova
1个回答
1
投票

查看

count()
方法的文档:

/**
 * Return a value result showing the growth of an count aggregate over time.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Illuminate\Database\Eloquent\Builder|class-string<\Illuminate\Database\Eloquent\Model>  $model
 * @param  \Illuminate\Database\Query\Expression|string|null  $column
 * @param  string|null  $dateColumn
 * @return \Laravel\Nova\Metrics\ValueResult
 */
public function count($request, $model, $column = null, $dateColumn = null) {
    return $this->aggregate($request, $model, 'count', $column, $dateColumn);
}

第四个参数可以指定使用哪一列进行日期聚合。
因此,请尝试:

public function calculate(NovaRequest $request) {
    return $this->count($request, Order::onlyCompleted(), null, 'completed_by_manager_at');
}
© www.soinside.com 2019 - 2024. All rights reserved.