通过laravel集合格式化数据集



我有两个模型RolesSpecialisation,它们都以hasManybelongsTo的关系相互关联。我有另一个名为Company的模型,它与它们中的每一个都是Many-to-many关系。我正在处理一个图表,其中我需要有一个数据集,如下所示:

data: {
Consultant: { "Avenger": 14, "Challenger": 647 },
Contractor: { "124 Spider": 4478, "500": 12685, "500L": 1664, "500X": 7665 },
Manufacturer: { "C-Max": 390, "Edge": 1423, "Escape": 308296, "E-Series": 53304, "Expedition": 5183, "Explorer": 2731, "Fiesta": 46249},
Miscellaneous: { "C-Max": 18390, "Edge": 142603, "Escape": 308296, "E-Series": 53304, "Expedition": 883, "Explorer": 2731 },
Owner: { "C-Max": 18390 },
Supplier: { "Expedition": 5883, "Explorer": 271131, "Fiesta": 46249, "Flex": 2289, "Focus": 1583 },
}

此处为ConsultantContractorManufacturer。。。etc表示role->name,在对象的索引内,我有specialisation->name和表示与之相关的公司计数的数字,我想用以下代码实现:

$data = Role::whereNull('parent_id')->get();
$roles = collect($data)->map(function ($role) {
$specialisation = Specialisation::where('parent_id', $role->id)->get();
$element[$role->name] = array(
//specialisation and companies_count
);
return $element;
});

我对实现这一点有点困惑。帮我解决这个问题。欢迎提出任何建议。谢谢

我无法从collection方法中找到任何解决方案。为了实现这一点,我尝试在stdClass()的帮助下创建一个对象,然后在对象内部创建另一个对象并返回整个数据。类似这样的东西:

$data = Role::whereNull('parent_id')->withCount('companies')->get();
$object = new stdClass();
foreach($data as $key => $value)
{
$name = $value->name;
$specialisation = Specialisation::where('parent_id', $value->id)->withCount('companies')->get();
$ob = new stdClass();
foreach ($specialisation as $sp => $spec)
{
$n = $spec->name;
$ob->$n = $spec->companies_count;
}
$object->$name = $ob;
}
return response()->json(['data' => $object], 200);

希望这能帮助到别人。谢谢

相关内容

  • 没有找到相关文章

最新更新