【发布时间】:2020-02-10 10:58:03
【问题描述】:
我正在为posts 表构建一个搜索表单。
现在我可以搜索描述,但是当我选择一个类别或日期并搜索时,结果页面会显示所有帖子。这意味着“类别”和“日期”的搜索功能不起作用。
我不想构建严格的搜索功能,所以我使用了orWhere 查询子句。
web.php
Route::get('results', 'ResultsController@index')->name('posts.result');
ResultsController.php
public function index(Request $request)
{
$keyword = $request->get('keyword');
$category = $request->get('category_id');
$date = $request->get('date');
if ($keyword || $category || $date) {
$posts = Post::Where('keyword', 'LIKE', '%' . $keyword . '%')
->orWhere('category_id', $category)
->orWhere('date', $date)
->paginate(10);
return view('posts.result', compact('posts'));
} else {
$posts = Post::latest()
->orderBy('date', 'asc')
->paginate(10);
return view('posts.result', compact('posts'));
}
}
发布表迁移
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image');
$table->unsignedBigInteger('category_id');
$table->string('title');
$table->string('place');
$table->string('map');
$table->date('date');
$table->string('organizer');
$table->string('organizer_link');
$table->timestamp('published_at')->nullable();
$table->text('description');
$table->timestamps();
});
result.blade.php
<form action="{{ route('posts.result') }}" class="search" method="GET">
<input type="text" name="description" class="search_text" placeholder="Enter the key words">
<select name="category" id="select" class="Genre">
<option value="" hidden name="category">Category</option>
@foreach(App\Category::all() as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
<input type="text" name="date" class="search_date" id="date" placeholder="Choose date">
<button type="submit" class="test">
<i class="fas fa-search "></i>
</button>
</div>
</form>
【问题讨论】:
-
您有任何错误吗?究竟是什么不工作?我还看到您在类别和日期中使用 orWhere 而不喜欢。但如果不输入任何一个,您的查询将不会返回任何内容。所以如果它们存在的话,也许应该有条件地将它们添加到查询中?您假设如果其中任何一个存在,那么全部存在。我们无法从您的问题中看出这一点。
-
我没有收到任何错误。我的问题是,当我选择一个类别或日期并进行搜索时,结果页面会显示所有帖子。这意味着“类别”和“日期”的搜索功能不起作用。
-
你能分享一下dd($category, $date);价值观?
-
请在您的查询中添加这些作为条件。确保仅在它们确实传递了数据时才将它们添加到查询中。
-
@Mesuti 两个值都为空。
标签: php sql laravel forms search