【发布时间】:2020-07-05 14:12:32
【问题描述】:
好的,我正在我的 Laravel 项目中进行搜索,我正在使用 whereBetween 子句,但它无法正常工作。让我展示代码而不是解释。
这是我的SearchController 搜索功能:
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
*/
public function automobilipretraga(Request $request)
{
$autoQuery = DB::table('automobils');
if (
$from = $request->input('from')
&& $to = $request->input('to')
) {
$autoQuery->whereBetween('price', [$from, $to]);
}
//vracanje rezultata
$automobili = $autoQuery->get();
return view('site.automobili.pretraga')->with('automobili', $automobili);
}
在我的search.blade.php:
<div id="collapsecijena" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="cijena">
<div class="panel-body">
<div class="cs-model-year">
<div class="cs-select-filed">
<input type="text" name="from">
</div>
<span style="color:black;">TO</span>
<div class="cs-select-filed">
<input type="text" name="to">
</div>
</div>
</div>
</div>
所以我将这两个输入命名为 from 和 to。
例如,我有三个汽车帖子,第一个有一个price of 15,第二个有一个price of 45,第三个有一个price of 80。当我在20 and 50 之间搜索价格时它不起作用,它会显示带有price of 15 的汽车帖子,但是当我将搜索更改为10 and 30 之间时它可以工作。
就像它只计算$to 变量而不是from。
我做错了什么?
【问题讨论】:
-
这行得通吗?
$autoQuery->whereBetween('price', [$request->from, $request->to]); -
非常感谢,我认为它现在可以完美运行了!让我快速检查一下。为什么这是有效的,你能解释一下吗?
-
这里有问题
if ( $from = $request->input('from') && $to = $request->input('to') ) -
我应该如何处理那行代码?只需将其删除并保留为
if { $autoQuery->whereBetween('price', [$request->from, $request->to]); }? -
我回答了你的问题,我从中学到了一些特别的东西,谢谢
标签: php laravel search eloquent where-clause