Lumen/Laravel Eloquent hasManyThrough 嵌套结果

Lumen/Laravel Eloquent hasManyThrough nested results

我正在尝试使用 Laravel Eloquent 获得嵌套结果。

我的逻辑: 城市、社区、街区

一个城市有很多街区

一个街区有很多街区

我要完成的结果:

City
 Neighbourhoods
  Blocks

数据应该是:

[
  {

    id: 1,
    name: "New York",
    neighbourhoods: [
      {
        id: 1,
        name: "Neighbourhood 1",
        city_id: 1,
        blocks: [
          {
            id: 1,
            name: "Neighbourhood 1 Block 1",
            neighbourhood_id: 1
          },
          {
            id: 2,
            name: "Neighbourhood 1 Block 2",
            neighbourhood_id: 1
          }
        ]
      },
      {
        id: 2,
        name: "Neighbourhood 2",
        city_id: 1,
        blocks: [
          {
            id: 3,
            name: "Neighbourhood 2 Block 1",
            neighbourhood_id: 2
          },
          {
            id: 4,
            name: "Neighbourhood 2 Block 2",
            neighbourhood_id: 2
          }
        ]
      }
    ]
  }
]

型号:

City.php

public function neighbourhood()
{
    return $this->hasMany('App\Neighbourhood');
}

public function block()
{
    return $this->hasManyThrough('App\Block', 'App\Neighbourhood', 'city_id', 'neighbourhood_id', 'id');
}

Neighbourhood.php

public function city()
{
    return $this->belongsTo('App\City');
}

public function block()
{
    return $this->hasMany('App\Block');
}

Block.php

public function neighbourhood()
{
    return $this->belongsTo('App\Neighbourhood');
}

实际结果是这样的:

[
    {
        "id": 1,
        "name": "Ney York",
        "neighbourhoods": [
            {
                "id": 1,
                "city_id": 1,
                "name": "Heighbourhood 1"
            },
            {
                "id": 2,
                "city_id": 1,
                "name": "Heighbourhood 2"
            },
            {
                "id": 4,
                "city_id": 1,
                "name": "Păcurari"
            }
        ],
        "blocks": [
            {
                "id": 1,
                "name": "Heighbourhood 1 Block 1",
                "neighbourhood_id": 1,
                "city_id": 1
            },
            {
                "id": 2,
                "name": "Heighbourhood 1 Block 2",
                "neighbourhood_id": 1,
                "city_id": 1
            }
        ]
    }
]

我想要嵌套结果。有没有办法做到这一点?我遗漏了什么?

当然我可以用 PHP foreach 循环来完成,但这将是手动工作。请问这种方式能不能直接从查询中得到结果

谢谢。

解决方案:

$result = City::with('neighbourhoods.blocks')->get();

应该这样做:

$result = City::with('neighbourhoods.blocks')->get();

您可以使用圆点表示法进行嵌套 relationship queries