我有两个模型,Roles
并且Specialisation
它们都相互hasMany
关联belongsTo
。我有另一个模型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 },
}
这里Consultant
, Contractor
, Manufacturer
, ... 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;
});
我对实现这一点有点困惑。帮我解决这个问题。欢迎任何建议。谢谢。