Laravel 从集合中计数值

问题描述

如何得到这些数据相乘的总和。

这是我的kvit

ByValue

这是操作

ByReference

这里是关系

id | hamkor_id | oper_type 
1  |  10       |     20     

这里是控制器

id | kvit_id | product_id | store_id| amount | price 
1  |     1   |     5      |    1    |    10  |   15
2  |     1   |     6      |    1    |    5   |   10

这是我的观点

class Kvit extends Model
{
use HasFactory;

public function operation(){
    return $this->hasMany(Operation::class);
}

public function hamkor(){
    return $this->belongsTo(User::class,'hamkor_id','id');
}

public function user(){
    return $this->belongsTo(User::class);
}

public function store(){
    return $this->belongsTo(Store::class);
 }
}

我需要通过将每个产品的数量乘以价格来获得总金额。 那是收据的总金额 像这样 (1015 + 510) = 200 怎么可能?

解决方法

如果我理解正确,您要计算sum表中amount * price列的Operation,按kvit_id分组吗?

您可以通过向 Kvit 模型添加 custom attribute 来解决此问题。

// Kvit model
class Kvit extends Model
{
    public function getTotalPriceAttribute(): float
    {
        return $this->operation->sum( function($operation) {
            return $operation->amount * $operation->price;
        });
    }
}

在您的 Blade 视图中,您只需调用:

{{ $data->kvit->total_price }}

这是解决您问题的一种方法。

几点说明:

  1. operation 是一个 HasMany 关系,所以不应该复数吗? (operations)?
  2. 我使用了 float 作为返回类型,但这可能是一个整数,具体取决于您的实现。
  3. 您可以从 $idx => 中删除 foreach。相反,您可以使用 Loop variable 并调用 {{ $loop->iteration }} 而不是 {{ $idx + 1 }}

完整示例:

class Operation
{
    public $amount;
    public $price;

  
    public function __construct($amount,$price)
    {
      $this->amount = $amount;
      $this->price = $price;
    }
}

class Kvit
{
    public $operations;
  
    public function __construct($operations)
    {
      $this->operations = $operations; 
    }
  
    public function calculate(): float
    {
        return $this->operations->sum( function($operation) {
            return $operation->amount * $operation->price;
        }); 
    }
}

$operation1 = new Operation(10,15);
$operation2 = new Operation(5,10);

$operations = collect([$operation1,$operation2]);

$kvit = new Kvit($operations);

$kvit->calculate(); // returns 200
,

这不是测试它,我现在没有任何例子,但也许你可以解决这样的问题。在kvit模型类中创建方法

public function self_amount()
{
   $sum = 0;
   if($this->operation()->exists()) // or count($this->operation)
     $operation = $this->operation->filter(function($item) use ($sum) {
        $sum += $item->amount * $item->price;
     });
   return $sum;
}

在刀片中

<td>{{$data->self_amount()}}</td>