【问题标题】:How to get count of second level hasMany relation through first level of hasMAny in laravel如何通过laravel中的第一级hasMANy获取第二级hasMany关系的计数
【发布时间】:2020-01-27 15:24:53
【问题描述】:

我的关系为 building hasMany floorsfloor hasMany units。 我想知道每栋建筑的单位数。

我可以很容易地获得楼层数:

$building = Building::findOrFail($id);
$building->floors()->count();

但是,我无法获得单位数:

$building = Building::findOrFail($id);
$building->floors()->units()->count();

我的口才关系如下:

Building
--------
    public function floors()
    {
        return $this->hasMany('App\Models\Floor');
    }
Floor
--------
    public function units()
    {
        return $this->hasMany('App\Models\Unit');
    }

我想要的只是根据建筑物获取单元数。

【问题讨论】:

  • 您可能需要在BuildingUnits 之间有一个hasManyThrough(),否则您需要遍历floors(),因为floors()->units() 没有逻辑意义。 $floor->units() 将(单个Floor 实例),但floors()->units(),作为Floor 实例的Collection 不允许直接访问units(),因为它不知道是哪一个。跨度>

标签: laravel


【解决方案1】:

将此功能放入建筑模型中:

    public function units()
    {
        return $this->hasManyThrough('App\Models\Unit', 'App\Models\Floor');
    }

那么你就可以轻松做到了:

$building->units()->count();

【讨论】:

  • 如果我需要从第三级关系中获取计数怎么办。可以说,来自殖民地。如1殖民地有很多建筑,建筑有很多楼层,楼层有很多单元。那么,我怎样才能从菌落模型中得到这个计数呢?
  • 那么你可以使用这个包:github.com/staudenmeir/eloquent-has-many-deep
猜你喜欢
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2017-11-15
  • 2019-04-04
  • 1970-01-01
  • 2020-04-29
  • 2014-08-02
相关资源
最近更新 更多