通过 Laravel 中的某些属性创建条目组并返回它们的更好方法

Better approach to making groups of entries by some attribute in Laravel and returning them

我正在 Laravel 中制作一些 API,我想 return JSON 这样的回应:

{
    "attribValue1": [entries],
    "attribValue2": [entries],
    "attribValue3": [entries]
}

所以我对数据库提出了这些请求:

$attribValue1 = Partner::where([['partner_type', '=', 'attribValue1'], ['enabled', '=', true]])->orderBy('position', 'asc')->get();
$attribValue2 = Partner::where([['partner_type', '=', 'attribValue2'], ['enabled', '=', true]])->orderBy('position', 'asc')->get();
$attribValue3 = Partner::where([['partner_type', '=', 'attribValue3'], ['enabled', '=', true]])->orderBy('position', 'asc')->get();

return compact('attribValue1', 'attribValue2', 'attribValue3');

但我的问题是我不喜欢这个解决方案。它查询数据库三次,所以我正在寻找更好的解决方案。谁能帮帮我?

尝试:

$attribs = Partner::where('enabled', true)
    ->whereIn('partner_type', ['attribValue1', 'attribValue2', 'attribValue3'])
    ->orderBy('position', 'asc')
    ->get()->groupBy('partner_type');
`dd($attribs)`;

然后相应地使用数据。

你可以试试:

$attribs = Partner::where('enabled', true)
    ->whereIn('partner_type', ['attribValue1', 'attribValue2', 'attribValue3'])
    ->orderBy('position', 'asc')
    ->get()
    ->groupBy('partner_type');

dd($attribs->toArray()); // Show what you get.

现在,您有三个按属性分组的集合。所以很容易将其转换为JSON。有关集合 groupBy 的更多信息,请参见此处:https://laravel.com/docs/5.4/collections#method-groupby