Laravel Search Relationship

前端 未结 1 758
一整个雨季
一整个雨季 2021-02-01 22:54

I have two models which are related. I am trying to do a search in Products and only display the actual search results instead of ALL products of the category in which the produ

相关标签:
1条回答
  • 2021-02-01 23:13

    I don't know what how are you viewing the results, but I think if you just eager load the products on the categories you should be good.

    $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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题