【问题标题】:Remove duplicates in a foreach loop (but count them) - Laravel 8在 foreach 循环中删除重复项(但计算它们) - Laravel 8
【发布时间】:2022-01-23 21:01:18
【问题描述】:

我无法使用 Laravel 8 在 foreach 循环中删除重复的 IP(但计算它们)。它返回唯一的 IP,但返回所有行数而不是每个 IP 数。

表格

public function up()
{
    Schema::create('visitors', function (Blueprint $table) {
        $table->id();
        $table->string('ip');
        $table->string('url');
        $table->string('city');
        $table->string('state');
        $table->string('country');
        $table->string('browser')->nullable();
        $table->string('device')->nullable();
        $table->timestamps();
    });
}

控制器

public function show()
{
    $data = Visitor::select('ip','url','city')->distinct('ip')->get();
    
    return view('admin.visitors.index', compact('data'));
}

刀片

 @foreach($data as $data)
    <tr>
       <td>{{ $i++}}</td>
       <td class="col-md-3">{{ $data->ip }} </td>
       <td class="col-md-3">{{ $data->count() }} </td>
       <td class="col-md-3">{{ $data->url }} </td>
       <td class="col-md-3">{{ $data->city }} </td>
       <td class="col-md-3">{{ $data->state }} </td>
    </tr>
@endforeach









 

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

    你想使用计数和分组功能的组合:

    $records = Visitor::selectRaw('ip, count(ip) as ipcount, url, city, state')->groupByRaw('ip, url, city, state')->get();
    

    这将返回 ip + url + city + state 的唯一组合计数。

     @foreach($records as $record)
        <tr>
           <td>{{ $i++}}</td>
           <td class="col-md-3">{{ $record->ip }} </td>
           <td class="col-md-3">{{ $record->ipcount }} </td>
           <td class="col-md-3">{{ $record->url }} </td>
           <td class="col-md-3">{{ $record->city }} </td>
           <td class="col-md-3">{{ $record->state }} </td>
        </tr>
    @endforeach
    

    【讨论】:

    • 非常感谢 Ausista_z - 它工作得正是我想要的代码。现在,除了唯一的 ip,我也得到了他们的重复计数。祝你好运。
    • 这工作正常,我现在看到的唯一问题 - 无法获取使用此查询创建的 _at。当我在上面的查询中添加 created_at 时,它会获取所有行。如何同时实现 fetch created_at 呢?
    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2014-06-05
    • 2016-03-21
    • 2012-02-15
    相关资源
    最近更新 更多