Laravel雄辩的查询生成器-与关系组的总和

时间:2019-04-24 16:39:32

标签: php mysql laravel eloquent laravel-query-builder

我正在寻找以下方面的查询构建器解决方案:

表:transaction_types

| id | type_hash | description     | category |
|----|-----------|-----------------|----------|
| 1  | abcd      | sale price      | sale     |
| 2  | dbac      | sale tax        | sale     |
| 3  | agft      | sale shipping   | sale     |
| 4  | pgsk      | refund price    | refund   |
| 5  | sa2r      | refund tax      | refund   |
| 6  | sdf4      | refund shipping | refund   |

表:交易

| id | type_hash | amount |
|----|-----------|--------|
| 1  | abcd      | 12     |
| 2  | dbac      | 14     |
| 3  | agft      | 19     |
| 4  | pgsk      | -20    |
| 5  | sa2r      | -12    |
| 6  | sdf4      | -7     |

关系-交易属于交易类型

public function transactionType() : BelongsTo
{
    return $this->belongsTo(TransactionType::class, 'type_hash', 'type_hash');
}

我要在交易表上查找的结果是:

  • 总计sum(amount) as amount
  • TransactionType.category分组交易

| Results | transactionType.category | sum(amount)   |
|---------|--------------------------|---------------|
| 1       | sale                     | 45            |
| 2       | refund                   | -39           |

我可以完成以下工作,但理想情况下,我想在查询构建器中而不是在集合中进行所有聚合:

Transaction::selectRaw('sum(amount) as amount')
    ->with('transactionType')
    ->get()
    ->groupBy('transactionType.category');

我已经尝试了以下方法(及其变体),但无法使其正常工作:

Transaction::selectRaw('sum(amount) as amount')
    ->with(['transactionType' => function($query){
        $query->select('category')->groupBy('category');
    }])
    ->get();

1 个答案:

答案 0 :(得分:0)

在生成的SQL中,您需要选择分组的列,并且需要在groupBy之后调用get(),否则您将在集合上调用groupBy ,而不是查询构建器对象。因此,您应该可以:

Transaction::selectRaw('transactionType.category, sum(amount) as amount')
->with('transactionType')
->groupBy('transactionType.category')
->get();

或不太口才

DB::table('transaction')
->join(
    'transaction_type',
    'transaction_type.id',
    '=',
    'transaction.transaction_type_id'
)->selectRaw('transationType.category, sum(amount)')
->groupBy('transactionTyle.category')
->get();