html - 如何在laravel中实现html表与mysql数据的排序功能?

标签 html mysql laravel

我目前正在尝试弄清楚如何为显示在 html 表中的 mysql 数据实现排序功能。我已经有了实现此目的所需的查询,但我想知道当用户单击特定列时如何在每个查询之间实现和切换。我正在使用 Laravel 构建这个项目,因此我的数据是通过 Controller 检索和压缩的。这是该 Controller 和我需要的查询:

class StatController extends Controller
{
    public function index() 
    {

    //$stats = Stat::all();

    $stats = Stat::orderBy('goals', 'DESC')->get();

    //$stats = Stat::orderBy('goals', 'ASC')->get();

    //$stats = Stat::orderBy('assists', 'ASC')->get();

    //$stats = Stat::orderBy('assists', 'DESC')->get();

    return view('stats.index', compact('stats'));

    }
}

这是我的 stats.index View 中的 HTML 表格:

<div class="all_tables stats_table table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Goals</th>
              <th>Assists</th>
            </tr>
          </thead>
          <tbody>

          @foreach ($stats as $stat)

            <?php

              $player = App\Player::find($stat->player_id);

            ?>

            <tr>
              <td>{{ $player->number }}</td>
              <td><a href="/players/{{ $player->id }}">{{ $player->fn }} {{ $player->ln }}</a></td>
              <td>{{ $stat->goals }}</td>
              <td>{{ $stat->assists }}</td>
            </tr>

          @endforeach

          </tbody>
        </table>
      </div>

如何让目标助攻列在用户点击时可排序?

最佳答案

在JQuery中使用DataTable插件,您只需要使用here中的datatable js文件即可

你的表格应该是这样的:

<table id="myTable">
    <thead>
        <tr>
              <th></th>
              ...
              ...
              <th></th>
        </tr>
   </thead>

   <tbody>
        <tr>
             <td></td>
             ...
             ...
            <td></td>
       </tr>
  </tbody>

添加js文件后,必须添加此脚本。

$(document).ready(function(){
   $('#myTable').DataTable();
});

关于html - 如何在laravel中实现html表与mysql数据的排序功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867029/

相关文章:

html - 不寻常的 CSS 过渡行为。您可以禁用特定参数吗?

mysql - 如果太长停止 mysql 查询

javascript - 将html表格导出到一列上有tinymce的word

laravel - 从 Eloquent 关系中获取第一个元素

mysql - Vagrant SSH - 设置并连接到 MySQL

javascript - 从 Angular 指令调用的函数访问属性/$element 上下文

javascript - Datepicker 范围不允许退房日期为同一天

html - 为什么选取框在悬停时不停止?

mysql - 查询需要 30 多分钟 -- 我怎样才能加快速度? (包括解释和架构)

mysql - 我想从多个表中检索唯一数据我也想用记录显示其表名