代码之家  ›  专栏  ›  技术社区  ›  Bosshoss

从多个表中获取Json数组

  •  0
  • Bosshoss  · 技术社区  · 11 月前

    我的数据库中有两个表。

    device_category('id_category', 'name_category');
    device('id_device', 'name_device', 'category_device');
    

    我有一个 DeviceController 用一个 get() 方法

    public function get()
    {
        $devices = Device::select('*')
                     ->join('device_category','device_category.id_category','=','device.category_device')
                     ->get();
    
        return response()->json($devices, 200);
    }
    

    JSON结果是:

    [
        {
            "id_category": 1,
            "name_category": "Phone",
            "id_device": 1,
            "name_device": "iPhone 10"
        },
        {
            "id_category": 1,
            "name_category": "Phone",
            "id_device": 2,
            "name_device": "iPhone XS"
        },
        {
            "id_category": 2,
            "name_category": "Computer",
            "id_device": 3,
            "name_device": "Lenovo xx"
        }
    ]
    

    然后我将结果分组:

    $devices = $devices->groupBy('name_category');
    return response()->json($devices, 200);
    

    得到了这个JSON:

    {
        "Phone" : [
            {
                "id_category": "1",
                "id_device": 1,
                "name_device": "iPhone 10"
            },
            {
                "id_category": "1",
                "id_device": 2,
                "name_device": "iPhone XS"
            }
        ],
        "Computer" : [
            {
                "id_category": "2",
                "id_device": 3,
                "name_device": "Lenovo XX"
            }
        ]
    }
    

    我想要一个类别阵列,每个类别都有一个设备阵列,我如何才能得到这个结果?我可以在一个查询中完成吗?还是我需要获取类别然后设置设备?

    [
        {
            "id_category": 1,
            "name_category": "Phone",
            "device" : [
                {
                    "id_device": 1,
                    "id_category": 1,
                    "name_device": "iPhone 10"
                },
                {
                    "id_device": 2,
                    "name_device": "iPhone XS"
                }
            ]
        },
        {
            "id_category": 2,
            "name_category": "Computer",
            "device" : [
                {
                    "id_device": 3,
                    "name_device": "Lenovo XX"
                }
            ]
        }
    ]
    
    0 回复  |  直到 11 月前