Agu*_*u V 2 php laravel eloquent laravel-5
在 laravel 5.2 中,我有一个模型的分页表。
@CityController
public function index(Request $request){
$cities = City::orderBy('name');
return view('pages.city.index', ["cities" => $cities ->paginate(25)]);
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但是当我尝试对刀片视图内的结果进行排序时不起作用。
@index.blade.php
<table>
<thead>
<tr class="sui-columnheader">
<th class="sui-headercell" data-field="Id">
<a href="{!! $cities->appends(['sort' => 'id'])->links() !!}">Id</a>
</th>
</thead>
<tbody class="list">
@foreach ($cities as $city)
<tr class="sui-row">
<td class="sui-cell id">{!! $city->id !!}</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
当我单击排序按钮时,只会重新加载页面,但不会应用排序。
是因为“orderBy”子句吗?我怎样才能让它工作并默认按名称排序?我错过了什么吗?
也许是这样的。您需要确保限制可以传递给该的内容orderBy。像“”这样的 URL...something?sort=blah会导致orderBy('blah'),而您的表没有该 URL,这将导致数据库错误。
public function index(Request $request)
{
$cities = City::orderBy($request->input('sort', 'name'))->paginate(25);
return view('pages.city.index', ['cities' => $cities]);
}
{{ $cities->appends(Request::query())->render() }}
Run Code Online (Sandbox Code Playgroud)
只是给您一个功能示例,但您必须根据自己的规则进行调整。
只是appends允许您通过分页链接的查询字符串传递排序选项,继续基于当前排序进行分页。
更新:
使用您的示例,其中有默认值,但想象可能不止 1 个其他字段可供排序:
$sort = trim($request->input('sort'));
// if it is in the acceptable array use it, otherwise default to 'name'
$sort = in_array($sort, ['id', ...]) ? $sort : 'name';
$cities = City::orderBy($sort)->paginate(25);
<table>
<tr>
<th><a href="{{ Request::fullUrlWithQuery(['sort' => 'id']) }}">ID</a></th>
<th><a href="{{ Request::url() }}">NAME</a></th>
...
</tr>
@foreach ($cities as $city)
<tr>
<td>{{ $city->id }}</td>
<td>{{ $city->name }}</td>
...
</tr>
@endforeach
...
{{ $cities->appends(Request::query())->render() }}
Run Code Online (Sandbox Code Playgroud)
只是一个例子,您可以按照自己的意愿进行操作。
| 归档时间: |
|
| 查看次数: |
8382 次 |
| 最近记录: |