我有一个搜索表单,可以更轻松地查找产品。不幸的是,它不是从我的输入中查询而只是返回所有字段......
public function index(Request $request)
{
//
$types = Category::all();
$products = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.product_id', '=', 'product.id')->select('product.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('id')->orderBy('ratings_average', 'DESC')->get();
$name=$request->input('name');
$type=$request->input('categories_id');
if(!empty($name)){
$products->Where('name', 'LIKE', '%'.$name.'%');
}
if(!empty($type)){
$products->Where('categories_id', 'LIKE', '%'.$type.'%');
}
return view('pages.search')->withProducts($products)->withTypes($types)
查看:
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
{!! Form::label('name', 'Search By Name:') !!}
{!! Form::text('name', null, array('class' => 'form-control')) !!}
</div>
{!! Form::label('categories_id', 'Search By Category:') !!}
<select class="form-control" name="categories_id" >
<option value=""></option>
@foreach($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
@endforeach
</select>
</div>
{!! Form::submit('Find Product', array('class' => ' btn-lg btn-block')) !!}
{!! Form::close() !!}
控制器:
Route::get('search', 'SearchController@index')->name('search.index');
任何想法为什么似乎都没有发生?
答案 0 :(得分:0)
请改用$products->where('name', 'LIKE', '%'.$name.'%');
。 (where
全部小写)
但更好的方法是在查询数据库本身时添加搜索条件,而不是获取所有结果,然后在结果集合上应用条件。
$productsQuery = Product::where('approved', '=', 1)
->leftJoin('reviews', 'reviews.product_id', '=', 'product.id')
->select('product.*', DB::raw('AVG(ratings) as ratings_average' ));
$name=$request->input('name');
$type=$request->input('categories_id');
if($request->has('name')){
$productsQuery->where('name', 'LIKE', '%'.$request->input('name').'%');
}
if($request->has('categories_id')){
$productsQuery->where('categories_id', 'LIKE', '%'.$request->input('categories_id').'%');
}
$products = $productsQuery->get();
答案 1 :(得分:0)
您应该在制作之前使用where where条件 - &gt; get()。 当您调用get()方法时,它会查询db。否则,您可以使用集合过滤器(在这种情况下不推荐)。