我可以在 Laravel 中的什么地方存储我的大 SQL 查询?

Where can I store my big SQL queries in Laravel?

我的 Laravel 结构有问题,因为我需要向我的应用程序添加许多报告,所以我认为将所有内容都放在控制器中不是一个好主意,因为我的 eloquent 模型允许我列出、添加、插入和更新,我的查询需要多个 table 和连接,以及一些数学函数,如 sum()、max()、min()。

当我使用 Codeigniter 时,我在模型文件中为每个查询添加了方法。 所以我可以调用它 $sales->salesReport() 它给了我数据。

Laravel 提供了类似于 Codeigniter 的东西,与您所描述的相匹配。它称为查询范围,或更准确地说是本地范围。您可以将它们保留在您的模型中,并在需要时随时调用它们。

您在模型中添加

public function scopeSalesReport($query) {
    return $query->join(...);
}

来源:https://laravel.com/docs/5.4/eloquent#local-scopes

问题实际上是关于正在做什么以及负责什么的问题。关于应在何处保留逻辑以及可以使用什么,有一些优秀的 posts。我不太清楚您是在询问链接范围之类的东西,还是只是在询问将逻辑放在哪里。我可能会有一个服务:

<?php

class SalesReportService {

    public function generateReport(Sales $sales)
    {
        // logic here...

        return $result;
    }

}

然后在控制器中它会是这样的:

<?php

class SalesController extends Controller {

    public function __construct(SalesReportService $reportService)
    {
        $this->reportService = $reportService;
    }

    public function show(Sales $sales)
    {
        return $this->reportService->generateReport($sales);
    }

}