如何使用 laravel eloquent 与关系相乘和分组

How to multiply and group using laravel eloquent with relation

我想从我的数据库中导出数据,但在使用 laravel eloquent 和关系

进行乘法和求和时遇到问题

所以我在那里有 2 个表(预算、项​​目)

预算:

// Table
+----+---------------+-----------------+------+-----+--------------------+
| id | delivery_plan | item_code       | curr | qty | price              |
+----+---------------+-----------------+------+-----+--------------------+
|  1 | 2022-08       | 201.0001        | IDR  |   1 |    2000.0000000000 |
|  2 | 2022-08       | 201.0001        | IDR  |   3 |    2000.0000000000 |
|  3 | 2022-07       | 201.9999        | IDR  |   2 |    2000.0000000000 |
+----+---------------+-----------------+------+-----+--------------------+

// Relation

public function item()
{
    return $this->belongsTo(Item::class, 'item_code', 'item_code');
}

条数:

// Table
+----+----------------+-----------+
| id | subgroup       | item_code |
+----+----------------+-----------+
|  1 | KOMPONEN MESIN | 201.0001  |
|  2 | EQUIPMENT LAIN | 201.9999  |
+----+----------------+-----------+

// Relation
public function budgets()
{
    return $this->hasMany(Budget::class, 'item_code', 'item_code');
}

所以,场景是:

  1. 将“数量”*“价格”列相乘并像这样将它们命名为“总计”
  2. 按来自 item() 关系的“子组”列对它们进行分组
  3. 按“delivery_plan”对它们进行分组

我更喜欢使用 eloquent 因为我需要那个“whereHas”方法来最小化复杂性 这是我到目前为止已经尝试过但没有用的方法:

$budgets = Budget::with('item', 'rate')->whereHas('period.term', function (Builder $builder) {
    $builder->where('name', '=', Session::get('term-budget'));
})->where('section', Session::get('section-budget'))->getQuery();

$result = $budgets->sum('price * qty')->get();

我怎样才能做到这一点?

这可以通过与 SUM() 的连接来解决,如下所示(未经测试):

Budget::leftJoin('items', 'budgets.item_code', '=', 'items.item_code')
    ->addSelect('subgroup')
    ->addSelect('delivery_plan')
    ->addselect(\DB::raw('SUM(qty * price) as total'))
    ->groupBy('subgroup', 'delivery_plan')
    ->get();