首页 > 解决方案 > 使用关系模型对数组的输出进行排序

问题描述

我正在尝试获取数组的结果,例如:

array:3 [▼
  0 => array:2 [▼
    "name" => "Sedan Car"
    "total" => 3089.0
  ]
  1 => array:2 [▶]
  2 => array:2 [▶]
]

但不幸的是,我的代码得到了:

array:3 [▼
  0 => array:3 [▼
    "car_id" => 5
    "total" => 3089.0
    "vehicle_class" => array:13 [▼
      "id" => 5
      "type" => "Standard Car"
      "name" => "Sedan Car"

我的控制器:

$target = Invoice::select('car_id')
            ->selectRaw("SUM(total_price) AS total")
            ->with('vehicleClass')
            ->groupBy('car_id')
            ->get()
            ->toArray();

 dd($target);

    $data = \Lava::DataTable();
    $data->addStringColumn('Country')
              ->addNumberColumn('Popularity');
    foreach($target as $row){
        $data->addRow([$row['car_id'], $row['total'] ]);
        $ket["totalTarget"] += $row['total'];
    }
    \Lava::DonutChart('Don', $data, [
                'title' => $balanceT,
                'height' => '300',
                'is3D'   => true,
            ]);

发票型号:

public function vehicleClass()
{
    return $this->belongsTo(VehicleClass::class,'car_id');

}

所以我的问题是如何从关系模型中获取 name 的值并将其添加到数组中并获得 total_price 列的 SUM “total”

为了更清楚:

  1. 发票型号和表格包含 [car_id, total_price]
  2. 车辆类模型和表包含 [名称,..etc]

    • 我需要 [name, Sum [total_price] ] name = card_id => 在关系模型中的结果

预先感谢您的帮助

标签: phplaravellaravel-query-builder

解决方案


希望这可以帮助:

$Data = Invoice::select('car_id', 'total')
            ->selectRaw("SUM(total_price) AS total")
            ->with([
                'vehicleClass'=>function($q) {
                    $q->select('id', 'name');
                }
            ])->get();

dd($Data->first()->vehicleClass->name);

据我所知,直接以你想要的方式获取数据是不可能的,除非你使用 Laravel Mutators。在里面Invoice附加以下内容:

protected $appends = ['car_name', 'total_price'];

public function getCarNameAttribute($value)
{
    return $this->vehicleClass()->select('id', 'name')->first()->name;
}

public function getTotalPriceAttribute($value)
{
    return $this->selectRaw("SUM(total_price) AS total")->where('id', $this->id)->first()->total;
}

然后,当您要检索汽车名称时,可以执行以下操作:

dd($Data->first()->car_name);
dd($Data->first()->total_price);

推荐阅读