【问题标题】:Table Joins in Laravel controllerLaravel 控制器中的表连接
【发布时间】:2022-01-04 01:44:56
【问题描述】:

我正在加入以在控制器中创建正确的表连接。目标是创建一个汇总表。

我当前的代码如下

$aircraftCosts = flight::with([
        'FuelUsage' => function ($query) {
            $query->where('campID', $campid);
        },
    ])
    ->select('aircraftID')
    ->selectRaw('(Sum(fullstopLandings)*30) as fullstopLandings') //Get Total of Fullstop Landings
    ->selectRaw('Sum(flightTotal) as flightTotal') //Get Total of Flight Income
    ->selectRaw('Sum(flightTotal) - (Sum(fullstopLandings)*30) as balance')
    ->selectRaw('Sum(price as fuelCost')
    ->where('campID',$campid)
    ->groupBy('aircraftID')
    ->get();

我有以下表格

fuel_records

id | aircraftID | fuelamount | price | fueldate | campID | fullstopLandings |

航班

id | aricraftID | hours | flightTotal 

飞机

id | registration | 

我的飞机模型上有以下内容

public function Flights()
    {
        return $this->hasMany('App\Flight', 'aircraftID', 'id');
    }

    public function HoursFlown()
    {
        return $this->hasMany('App\Flight', 'aircraftID', 'id')->sum('hours');
    }

    public function FuelUsage()
    {
        return $this->hasMany('App\FuelRecord', 'aircraftID', 'id');
    }

我要创建的是要在下面显示的汇总表

Aircraft | Movement Costs |Fuel Costs | Flight Income | Balance

我可以获得除燃料成本之外的每个项目的摘要,因为它存储在不同的表中。

我知道我的移动成本在这里是硬编码的,这将被移动到一个变量中,只是尝试先从数据构建表格

【问题讨论】:

  • 为什么不使用普通连接?
  • 为什么不创建一个视图并在那里检索所有信息表单???

标签: mysql laravel


【解决方案1】:

您可以使用 Join 函数代替 Eloquent Relationship。

flight::leftJoin("fuel_records AS fr", "fr.aircraftID" "flights.aircraftID")
  ->select('aircraftID')
  ->selectRaw('(Sum(fr.fullstopLandings)*30) as fullstopLandings') //Get Total of Fullstop Landings
  ->selectRaw('Sum(flights.flightTotal) as flightTotal') //Get Total of Flight Income
  ->selectRaw('Sum(flights.flightTotal) - (Sum(fr.fullstopLandings)*30) as balance')
  ->selectRaw('Sum(fr.price as fuelCost')
  ->groupBy("flights.aircraftID")
  ->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2019-10-09
    相关资源
    最近更新 更多