【问题标题】:Lumen/Laravel Eloquent hasManyThrough nested resultsLumen/Laravel Eloquent hasManyThrough 嵌套结果
【发布时间】:2017-08-22 21:10:17
【问题描述】:

我正在尝试使用 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
          }
        ]
      }
    ]
  }
]

型号:

城市.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');
}

块.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();

【问题讨论】:

    标签: php laravel eloquent has-many-through lumen


    【解决方案1】:

    应该这样做:

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

    您可以使用点符号进行嵌套relationship queries

    【讨论】:

    • 天哪!你不知道你救了我多少!非常非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-08-14
    • 2020-03-07
    • 2016-09-24
    • 2020-10-14
    • 2021-12-27
    • 2016-08-21
    • 2021-08-23
    • 2016-09-26
    相关资源
    最近更新 更多