代码之家  ›  专栏  ›  技术社区  ›  Philipp Kishkovarov

PHP数学方法

  •  1
  • Philipp Kishkovarov  · 技术社区  · 7 年前

    我的 Share 类HasMany Grant 类(相关)。 我的 grants 表具有 shares_amount .

    所以我显示了总数 股份金额 为每个 分享 使用此函数初始化:

    public function totalIssued()
    {
        return $this->grants->sum('shares_amount');
    }
    

    一切都是正确的。

    但现在我需要找到每个 totalIssued() 每个功能 分享 班级。

    屏幕截图将有助于: http://joxi.ru/Y2LBgLyi9EpLDr

    请给我小费。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Chin Leung    7 年前

    带循环

    假设你收集了 Share :

    $shares = \App\Share::all();
    

    然后,为了检索总数,您可以循环遍历它们中的每一个,将其求和为一个总变量。

    $total = 0;
    $shares->each(function ($share) use (&$total) {
        $total += $share->totalIssued();
    });
    

    或者通过 foreach 循环:

    $total = 0;
    foreach ($shares as $share) {
        $total += $share->totalIssued();
    }
    

    无回路

    \App\Share::join('grants', 'shares.id', '=', 'grants.share_id')
        ->sum('grants.shares_amount');