【发布时间】:2015-10-30 13:23:34
【问题描述】:
我有两个相关的模型。我正在尝试在 Products 中进行搜索,并且只显示实际搜索结果,而不是显示该产品所在类别的所有产品。我不想搜索任何类别,因为无论搜索什么或找到什么,这些类别都会始终显示。
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
【问题讨论】:
-
你想要的输出是什么?如若“Example”属于“Category 1”、“Category 2”和“Category 3”,您希望输出如何显示?
-
抱歉,我不太明白您想从查询中得到什么,是类别列表还是产品列表?
-
我更新了我的问题以更好地解释它:) 我想显示一个类别列表,包括链接到该类别的产品。
标签: php laravel search relation