【问题标题】:How to sum of function value from related table?如何对相关表中的函数值求和?
【发布时间】:2018-05-18 19:01:44
【问题描述】:

我有两个类:Share 和相关的EquityGrant

我在EquityGrant 中有这个数学函数

public function share() //relationship
{
    return $this->belongsTo(Share::class, 'share_id');
}
public function capitalCommitted() //my math function
{
    return $this->share_price * $this->shares_amount;
}

但是现在我需要返回我的capitalCommitted() 函数的Share 类总和,而我被卡住了。

我的Share班级:

public function grants() //relationship
{
    return $this->hasMany(EquityGrant::class);
}
public function totalIssued() //sum, works good
{
    return $this->grants->sum('shares_amount');
}
public function totalCommitted() //Stuck here
{
    //need help here, Must be like this: array_sum($this->grants->capitalCommitted());
}

【问题讨论】:

  • 怎么样: public function totalCommitted() { return $this->grants->sum(DB::raw('share_price * share_amount')); }
  • 返回 0 值

标签: php laravel function eloquent sum


【解决方案1】:

使用这个:

public function getCapitalCommittedAttribute()
{
    return $this->share_price * $this->shares_amount;
}

public function totalCommitted()
{
    return $this->grants->sum('capitalCommitted');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2019-08-25
    • 1970-01-01
    • 2022-11-03
    • 2019-01-21
    相关资源
    最近更新 更多