【问题标题】:Laravel: Show title for groupby in viewLaravel:在视图中显示 groupby 的标题
【发布时间】:2018-03-08 09:01:02
【问题描述】:

我想显示一个联系人列表,按 db 表中的“类型”列分组。我可以显示所有联系人,但如何在每个组上方显示每个“类型”的标题?我应该使用 groupby 还是 distinct?

期望的输出:

类型 1(作为 h2)

联系方式
联系方式
联系方式

类型 2

联系方式
联系方式
联系方式

等等……

表结构:
类型|姓名|电话|网址|等

路线:

`Route::get('/contacts', function () {
$contacts = DB::table('contacts')->get();
return view('pages.contacts', ['contacts' => $contacts]);
});`

观点:

`@if(isset($contacts))
@foreach($contact as $key => $contacts)
<h2>type name</h2>
<strong>{{$contacts->name}}</strong><br>
{{$contacts->phone}}<br>
{{$contacts->url}}
@endforeach
@endif`

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    尝试在控制器中将联系人分成两种类型。然后将它们都传递给视图。它看起来像这样:

    Route::get('/contacts', function () {
       $contactsType1 = DB::table('contacts')->where('type', '=', 'type1')->get();
       $contactsType2 = DB::table('contacts')->where('type', '=', 'type2')->get();
       return view('pages.contacts', $contactsType1, $contactsType2);
    });
    

    然后,您的页面上会有两个 for 循环,每个循环相互独立:

    @foreach($contactsType1 as $contact)
      --- display info as needed ----
    @endforeach
    -----
    @foreach($contactsType2 as $contact)
      --- display info as needed ----
    @endforeach
    

    【讨论】:

    • 每个“类型”有 20 多个联系人,大约 20 种类型。那么每种类型应该有 20+ 个变量?
    【解决方案2】:

    您可以对contacts 表中的所有类型进行分组并查询每种类型

    $group_types =  DB::table('contacts')->select('type')->groupBy('type')->get();
    
            @if(isset($group_types))
                @foreach($group_types as $type)
                    @foreach(\DB::table('contacts')->where('type',$type)->get() as $contacts)
                        <h2>type name</h2>
                        <strong>{{$contacts->name}}</strong><br>
                        {{$contacts->phone}}<br>
                        {{$contacts->url}}
                     @endforeach
                @endforeach
            @endif
    

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2017-06-14
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多