如何使用 laravel 数据库查询为 sql 中的分组项目命名?

How to give a name to the grouped items in sql with laravel db query?

使用这段代码我得到了这个输出:

$q = DB::table('payments')
        ->join('agency', 'agency.id', '=', 'payments.agency')
        ->join('paymenttype','paypemttype.id', '=', 'payments.paymenttype')
        ->select(DB::raw('sum(payment) as sum'), 'agency.agency', 'paymenttype.paymenttype')
        ->where('payments.school', '=', Sentry::getUser()->school)
        ->groupBy('payments.agency')
        ->groupBy('payments.paymenttype')
        ->get();

输出为:

[
{
sum: 200,
agency: "city1",
paymenttype: "credit card"
},
{
sum: 200,
agency: "city1",
paymenttype: "transfer"
},
{
sum: 200,
agency: "city2",
paymenttype: "credit card"
},
{
sum: 200,
agency: "city2",
paymenttype: "transfer"
}
  ]

但是我想要table左手边那个城市,所以我想要这种输出

-   city1  [
{
sum: 200,
paymenttype: "credit card"
},
{
sum: 200,
paymenttype: "transfer"
}],
- city2 [
{
sum: 200,
paymenttype: "credit card"
},
{
sum: 200,
paymenttype: "transfer"
}
  ]

所以我的意思是对象中的对象我想得到这样的数据。 如果你愿意帮助我,我会很高兴,再次感谢你的帮助。

您可以使用keyBy方法。

由于您没有使用 Eloquent,您可以自己创建一个 collection。

Laravel 5:

$result = collect($q)->keyBy('agency');

Laravel 4:

use Illuminate\Support\Collection;

$result = Collection::make($q)->keyBy('agency');