我有两个相关的型号.我试图在产品中进行搜索,并且只显示实际的搜索结果,而不是找到该产品所在类别的所有产品.我不想搜索任何类别,因为无论搜索什么,无论找到什么,这些类别都会一直显示出来.
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
So, what I WANT to achieve is the following. I do a search for a product called "Banana". What I WANT to be displayed is:
Category Food
- Product Banana
Category Drinks
- Product Banana Cocktail
Category Candy
- Product Banana Ice Cream
But my issue is, with my code, if I perform a search for "Banana", it displays the category in which banana is found, and it returns and displays ALL products in that category instead of ONLY the products that I searched for. How can I achieve it so only the products that was searched for are displayed?
类别型号:
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