我有这样的代码:

$totalCount = User::sum('count_fortress');

$lastVisit = User::orderBy('last_visit_fortress', 'DESC')->first('last_visit_fortress');

$topFiveUsers = User::whereNotNull(['count_fortress', 'last_visit_fortress'])
    ->orderBy('count_fortress', 'DESC')
    ->orderBy('last_visit_fortress', 'DESC')
    ->get(['id', 'count_fortress', 'last_visit_fortress'])
    ->take(5);

return response()->json([
    "fortress" => [
        "total_count" => $totalCount,
        "last_visited" => $lastVisit->last_visit_fortress,
        "users" => $topFiveUsers
    ]
]);


$totalCount = User::sum('count_museum');

$lastVisit = User::orderBy('last_visit_museum', 'DESC')->first('last_visit_museum');

$topFiveUsers = User::whereNotNull(['count_museum', 'last_visit_museum'])
    ->orderBy('count_museum', 'DESC')
    ->orderBy('last_visit_museum', 'DESC')
    ->get(['id', 'count_museum', 'last_visit_museum'])
    ->take(5);

return response()->json([
    "museum" => [
        "total_count" => $totalCount,
        "last_visited" => $lastVisit->last_visit_museum,
        "users" => $topFiveUsers
    ]
]);


有没有一种方法可以使它成为一种方法,或者像将逻辑放入控制器或服务而不是控制器中?

最佳答案

您可以在用户模型定义中使用范围来重用查询。

public function scopeTopFiveUsers(Builder $query, string $context) {
    ->whereNotNull(['count_' . $context, 'last_visit_' . $context])
    ->orderBy('count_' . $context, 'DESC')
    ->orderBy('last_visit_' . $context, 'DESC')
    ->select(['id', 'count_' . $context, 'last_visit_' . $context])
}


由于这两种解决方案之间存在关联,因此可以巧妙地使用列名和基于{}的字符串访问属性。该解决方案处于变得聪明的边缘,但这是一种不重复自我的思路。还利用了示波器解决方案。

private function calculateResponse(string $context) {
    $topFiveUsers = User::topFiveUsers($context)->take(5);
    $lastVisit = User::orderBy('last_visit_' . $context, 'DESC')->first('last_visit_' . $context)->{'last_visit_' . $context};

    return [
        'total_count' => User::sum('count_' . $context),
        'last_visited' => $lastVisit,
        'users' => $topFiveUsers
    ]
}

public function controllerMethodOne() {
    return response()->json([
        "fortress" => [
            $this->calculateResponse('fortress');
        ]
    ]);
}

public function controllerMethodTwo() {
    return response()->json([
        "museum" => [
            $this->calculateResponse('museum');
        ]
    ]);
}

关于php - Laravel- Eloquent 人不要重复自己,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59976387/

10-14 05:26