mysql - 在 Laravel 中不使用按钮和 ajax 自动过滤
问题描述
我有 3 张桌子:
Type: id, name
Level: id, name
Question: id, content, type_id, level_id
我已经用“过滤器”按钮完成了过滤功能。但是现在,我想要的是,当我过滤时,数据会自动加载到表中,而无需使用按钮。我能怎么做?
这是我使用按钮的代码
过滤控制器:
public function filter(Request $request){
$types = Type::all();
$levels = Level::all();
$model = Question::where('id', '>', 0);
if (isset($request->type))
$model = $model->where('type_id', $request->type);
if (isset($request->level))
$model = $model->where('level_id', $request->level);
$data = $model->paginate(999)->appends(request()->query());
return view('filter', compact( 'data', 'request', 'types','levels'));
}
过滤器.blade.php
<form method="get">
<select name="type">
<option value="">All Types</option>
@foreach ($types as $item)
<option value="{{ $item->id }}" @if ($request->type == $item->id) selected @endif>{{ $item->name }}</option>
@endforeach
</select>
<select name="level">
<option value="">All Levels</option>
@foreach ($levels as $item)
<option value="{{ $item->id }}" @if ($request->level == $item->id) selected @endif>{{ $item->name }}</option>
@endforeach
</select>
<button type="submit" class="btn btn-primary">Filter</button>
</form>
<table border="1">
<tr>
<th>ID</th>
<th>Content</th>
</tr>
@foreach ($data as $q)
<tr>
<td>{{ $q->id }}</td>
<td>{{ $q->content }}</td>
</tr>
@endforeach
</table>
解决方案
当您的选择值更改时,您可以简单地提交表单:
<select onchange="this.form.submit()">
...
</select>
或者,如果您不想使用表单,假设您的路径是/questions
并且您已经APP_URL
在 .env 文件中设置了属性,您可以执行类似于以下的操作:
<select name="type" onchange="window.location.href = this.value">
<option value="{{ url('questions') }}">All types</option>
@foreach($types as $type)
<option value="{{ url('questions') }}?type={{ $type->id }}"{{ request('type') == $type->id ? ' selected' : '' }}>
{{ $type->name }}
</option>
@endforeach
</select>
如果您希望在按类型过滤时保持当前选择的级别,您可以将选项值更改为以下内容:
<option value="{{ url('questions') . '?' . (request()->filled('level') ? 'level=' . request('level') . '&' : '') . 'type=' . request('type') }}">
{{ $type->name }}
</option>
在我的手机上回答,所以可能有语法错误。
推荐阅读
- c# - 反序列化对象列表会为空节点 .NET 创建一个新对象
- python - 基于 B 列分层的随机抽样,同时确保在所有层中至少选择一次 C 列的唯一值 - Pandas
- java - 检查 HashMap 是否包含另一个在 Java 中具有特定值的 HashMap
- python - Azure 机器学习工作室设计器 - 注册数据集时出现意外“创建新版本”
- f# - 如何实例化“类型化”地图?
- rest - 从 GetWorkItemsBetweenBuilds 返回的项目是独占集还是包含集?
- php - exec PHP 卡住加载
- r - data.frame 按列操作
- php - 修改子主题“Mikado Newsflash”上的 single.php
- google-apps-script - 如何将确切的字符串组合在一起?