【问题标题】:laravel 6. ActiveCount of sub relationship of sub relationshiplaravel 6. 子关系的子关系的ActiveCount
【发布时间】:2020-02-20 04:48:09
【问题描述】:

我正在构建具有 3 个模型(国家、部长、官员)的系统。

  1. 国家有很多部长;
  2. 每个部长都有很多官员

型号:国家

function ministers(){
    return $this->hasMany( Minister::class );
}

模特:部长

function officers(){
    return $this->hasMany( Officer::class );
}


function officersActiveCount(){
    return $this->hasMany( Officer::class)->where('state', 'active' )->count();
}

以下工作正常。它得到所有官员和相应的部长。

$nation = Nation::where('id', $nation_id)->with('ministers.officers')->get();

但我想得到 'ministers' 和 'officersActiveCount' 而不是 'officers'

我怎样才能得到每个国家的官员ActiveCount?

...

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    更改 Minister 模型上的关系并删除计数。关系中的计数将搞砸急切的加载。所以:

    function active(){
       return $this->hasMany( Officer::class)->where('state', 'active' );
    }
    

    现在您可以在 with() 方法上使用闭包并拉出该次要关系并使用 Larvel method withCount() 获取计数。

    类似这样的:

     $nation = Nation::where('id', $nation_id)->with(['ministers' => function($query){
            $query->withCount('active');
        }])->get();
    

    它应该是预先加载的,您可以通过 $nation 对象及其关系 ministers 访问活动计数:

     $activeOfficers = $nation->ministers->first()->active_count;
    

    这将为您提供该国第一部长的现役军官。如果你想把它们全部加起来,很容易循环:

    $totalActiveOfficersForNation = 0;
    foreach($nation->ministers as $minister){
        $totalActiveOfficersForNation += $minister->active_count;
    }
    

    还有其他方法可以计算列数,但这很简单。

    希望这会有所帮助。

    【讨论】:

    • 有关该故障的任何消息还是计算机刚刚开始冒烟? ;)
    • 'Call to a member function addEagerConstraints() on integer' 错误消息显示。我想知道如何将官员ActiveCount 表示为对象.. 它不应该与部长对象混合。
    • 感谢您的关注。我不擅长现代方式......对不起。
    • 嘿-我也是-不用担心。试试看。可能需要稍作调整才能使其正常工作。我还更改了模型关系名称以使其更易于理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多