php - 使用关系模型对数组的输出进行排序
问题描述
我正在尝试获取数组的结果,例如:
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”
为了更清楚:
- 发票型号和表格包含 [car_id, total_price]
车辆类模型和表包含 [名称,..etc]
- 我需要 [name, Sum [total_price] ] name = card_id => 在关系模型中的结果
预先感谢您的帮助
解决方案
希望这可以帮助:
$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);
推荐阅读
- android - 没有文本 R.string 链接可能?字符串 [] 名称 = {};
- python-3.x - 最高效的 one-hot-encoder
- java - 如何在 AKKA Actor 中实现线程安全?
- android - 如何使用 kotlin 文件流在 android 内部存储中存储自定义数据对象的数组
- r - 重新定位并增加使用 R 'plot' 函数生成的树状图周围的边界权重
- python - Tensorflow / Tflearn ValueError:无法为张量“输入/X:0”提供形状(4、11、11)的值,其形状为“(?、4、11、11)”
- java - 有人可以将这个 Java 正则表达式翻译成 Python 吗?
- c# - Xamarin UWP 似乎绑定到错误的视图模型
- c++ - 如何在c ++中将函数作为参数传递?
- tensorflow - How to convert RGB image to single channel image(but no grayscale) image