Laravel搜索关系

时间:2015-08-07 07:29:15

标签: php laravel search relation

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

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",它会显示找到banana的类别,并返回并显示该类别中的所有产品而不是仅我搜索过的产品。我怎样才能实现它,只显示搜索到的产品?

分类模型:

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

1 个答案:

答案 0 :(得分:23)

我不知道您是如何查看结果的,但我认为如果您只是急于在类别上加载产品,那么您应该很好。

$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;
    }
}