【问题标题】:Laravel pagination table - sort for one columnLaravel 分页表 - 为一列排序
【发布时间】:2017-08-19 07:38:42
【问题描述】:

我目前有以下:

<table class="table table-striped">
    <tr>
        <th> Artikelbild </th>
        <th> Artikelnummer </th>
        <th> Name des Artikels </th>
        <th> Beschreibung </th>
        <th> Preis </th>
        <th> Kategorie </th>
    </tr> @foreach($products as $product)
    <tr class='clickable-row' <?php if($product->stockCount === 0) echo "style='color:red;'";?>data-href="{{url('/product')}}
        <?php echo '/'.$product->id;?>">
        <td> <img src="/images/{{$product->imageUrl}}" class="productImageSmall" /> </td>
        <td> {{$product->id}} </td>
        <td> {{$product->name}} </td>
        <td>
            <?php if (strlen($product->description) > 30) { $productShortened = substr($product->description, 0, 30) . "[...]"; } else { $productShortened = $product->description; } echo $productShortened; ?> </td>
        <td>
            <?php echo number_format($product->price, 2, ',', '.');?>€ </td>
        <td> {{$product->categoryName}} </td>
    </tr> @endforeach
</table>

$product 是从我的控制器使用 paginate() 选项传递的。

现在我希望这张表可以按一列排序。假设用户点击表格顶部的“价格”(或德语中的 Preis)列,然后所有结果都应按价格排序(从低到高或从高到低),类别相同, 用于名称和其他所有列。

我该怎么做?我是否必须重新加载页面并再次从数据库中获取数据,但以某种方式排序(如果是,如何?)。或者我可以以某种方式对其进行排序而不重新加载它吗?我该怎么做?

感谢您的帮助

【问题讨论】:

    标签: javascript php jquery laravel sorting


    【解决方案1】:

    构建可排序表是一项非常耗时的任务,因此我建议您使用一些包。我使用this package 来构建可排序的表。

    如果您仍想自己构建此功能,您可以在 URL 中添加 ?price=desc 之类的参数,并使用 request() 方法获取这些参数。只是一个例子:

    if (request()->has('price')) {
        $query = $query->orderBy('price', request('price'));
    }
    

    别忘了append URL arguments to the pagination links:

    {{ $products->appends(['price' => 'desc'])->render() }}
    

    【讨论】:

    • 感谢您的回答。看起来你提供的包我可以做一些类似 $products::sorted()->paginate() 的事情,对吧?但它是否也提供了只需单击列即可按该列排序的功能,或者我该如何实现?
    • @nameless 是的,您可以这样做,是的,它提供了您描述的开箱即用的功能。这是一个非常酷的包,试一试。
    • 嘿,抱歉耽搁了,我有很多事情要做。看起来包裹与我想要的不同。我不想要一个可排序的表格,而是一个根据特殊列自动排序的表格,例如我点击名称然后表格按名称排序(从 az 开始),我点击价格表格是按价格排序(从低到高或其他方式),你知道我的意思吗?
    • @nameless 这正是这个包的作用。
    • 好的,那么演示中好像没有提供这个?你能给我一个例子来说明如何实现这个功能吗?
    猜你喜欢
    • 2023-03-10
    • 2014-12-10
    • 2019-11-24
    • 2015-06-10
    • 2022-11-11
    • 2018-12-12
    • 2014-02-24
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多