我有两个相关的模型。我正在尝试在产品中进行搜索,并仅显示实际的搜索结果,而不是在找到产品所属类别中的所有产品。我不想搜索任何类别,因为无论搜索什么和找到什么,类别都将始终显示。
Example. I have the following categories:
- Food
- Drinks
- Candy
My "Food" category has the following products:
- Strawberry
- Apple
- Banana
My "Drinks" category has the following products:
- Banana Cocktail
- Beer
- Cola
My "Candy" category has the following products:
- Strawberry Lollipop
- Chocolate Bar
- Banana Ice Cream
所以,我想要实现以下目标。我在搜索名为“香蕉”的产品。我想要显示的内容是:
Category Food
- Product Banana
Category Drinks
- Product Banana Cocktail
Category Candy
- Product Banana Ice Cream
但我的问题是,使用我的代码,如果我搜索“香蕉”,它会显示香蕉所在的类别,并返回并显示该类别中的所有产品,而不仅仅是我搜索的产品。如何做到只显示搜索到的产品?
分类模型:
class Categories extends Eloquent {
public function products()
{
return $this->hasMany('Products');
}
}
产品型号:
class Products extends Eloquent {
public function categories()
{
return $this->belongsTo('Categories');
}
}
我的控制器:
$searchString = Input::get('search');
if($searchString)
{
$categories = Categories::with('products')->orderBy($order, $by)->whereHas('products', function ($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
})->get();
}
else {
$categories = Categories::with('products')->orderBy($order, $by)->get();
}
我的观点:
@foreach($categories as $category)
{{ $category->name }} // Show the category name
@foreach($category->products as $product)
{{ $product->name }} // Show all products in that category
@endforeach
@endforeach