0

我有两个模型,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;
});

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

4

1 回答 1

0

我无法从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);

希望这对某人有所帮助。谢谢。

于 2019-11-14T10:01:37.687 回答