Laravel 5.6如何从列中获取重复数据

时间:2018-03-29 03:23:16

标签: mysql laravel

我希望打印每个topic_id的计数

show.blade.php

@foreach($questions as $question)
{{ $question->topic_id }}
@endforeach

ExamsController @索引

$topics = Topic::all();
return view('exams.show', compact('topics','questions'));

只想获取重复的数据并打印。

| id | topic_id |
| ---|:--------:|
| 1  |     4    |
| 2  |     9    |
| 3  |     5    |
| 4  |     5    |
| 5  |     2    |
| 6  |     4    |
| 7  |     5    |

我想要的结果是每个topic_id重复的计数。它喜欢

| id | topic_id |
| ---|:--------:|
| 1  |     4    |
| 6  |     4    |

2

| id | topic_id |
| ---|:--------:|
| 3  |     5    |
| 4  |     5    |
| 7  |     5    |

count = 3

3 个答案:

答案 0 :(得分:2)

您可以使用groupBy

$duplicates = Topic::selectRaw("count('id') as total, topic_id")
                   ->groupBy('topic_id')
                   ->get();

// pass the duplicates along with other variables to the view
return view('exams.show', compact('topics','questions', 'duplicates'));

在你看来你可以做到

@foreach ($duplicates as $duplicate)
{{ $duplicate->topic_id }} - {{ $duplicate->total }}
@endforeach

答案 1 :(得分:1)

也许您可以使用laravel上的集合功能按topic_id

对数据进行分组
$topic = Topic::all();
$topicArray = $topic->groupBy('topic_id')->toArray();

在您的视图中,您只需使用$ topicArray即可显示您的数据&算一下它的副本

@foreach ($topicArray as $key => $value)
  @foreach ($value as $key2 => $value2)
    | {{ $value2['id'] }} | {{ $value2['topic_id'] }} |<br>
  @endforeach
  count {{ count($value) }}<br><br>
@endforeach

答案 2 :(得分:0)

我不确定您的重复数据是什么,但我相信您正在寻找一个独特的数据。

  

distinct方法允许您强制查询返回distinct   结果   https://laravel.com/docs/5.6/queries#selects

$topics = Topic::distinct()->get();