Laravel 搜索关系

Laravel Search Relationship

我有两个相关的模型。我正在尝试在产品中进行搜索,并且只显示实际的搜索结果,而不是找到该产品的类别的所有产品。我不想搜索任何类别,因为无论搜索什么或找到什么,类别都会始终显示。

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

所以,我想要实现的是以下内容。我搜索了一个名为 "Banana" 的产品。我想要显示的是:

Category Food
- Product Banana

Category Drinks
- Product Banana Cocktail

Category Candy
- Product Banana Ice Cream

但我的问题是,对于我的代码,如果我搜索 "Banana",它会显示找到香蕉的类别,returns 并显示该类别中的所有产品而不仅仅是我搜索的产品。我怎样才能做到只显示搜索到的产品?

类别模型:

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

我不知道您如何查看结果,但我认为如果您只是急于将产品加载到类别中,那应该不错。

$categories = Categories::whereHas('products', function ($query) use ($searchString){
        $query->where('name', 'like', '%'.$searchString.'%');
    })
    ->with(['products' => function($query) use ($searchString){
        $query->where('name', 'like', '%'.$searchString.'%');
    }])->get();

foreach($categories as $category){
    echo $category->name . ':' . PHP_EOL;
    foreach($category->products as $product){
        echo . '-' . $product->name . PHP_EOL;
    }
}