Laravel不返回子类别结果

时间:2017-06-01 23:41:52

标签: php laravel search

我在Adding subcategories to laravel 5.4的帮助下向我的应用添加了子类别,在此之前,category上的搜索基础工作得很好我现在尝试更改subcategory上的搜索基础而且它没有不会返回结果。

这是我的搜索功能:

 public function search()
{
    $searchTitle = request('title');
    $searchCategory = request('subcategory');
    $searchLocation = request('location');

    $ads = null;

    if($searchTitle || $searchCategory || $searchLocation) {
        $ads = Ad::when($searchTitle, function ($query) use ($searchTitle) {
                return $query->where('title', 'like', "%{$searchTitle}%")
                    ->orWhere('description', 'like', "%{$searchTitle}%");
            })
            ->when($searchCategory, function ($query) use ($searchCategory) {
                return $query->whereHas('subcategory', function ($query) use ($searchCategory) {
                    $query->where('id', $searchCategory);
                });
            })
            ->when($searchLocation, function ($query) use ($searchLocation) {
                return $query->whereHas('location', function ($query) use ($searchLocation) {
                    $query->where('id', $searchLocation);
                });
            })
            ->paginate(10)
            ->appends(request()->query());
    }

    return view('search-result', compact('ads'));
}

这是我的搜索表单类别部分:

<label data-toggle="tooltip" data-placement="top" title="select category" class="sr-only mr-sm-2" for="inlineFormCustomSelect">Category</label>
              <select name="subcategory_id" data-toggle="tooltip" data-placement="top" title="select category"
                      class="custom-select mb-2 mr-sm-2 mb-sm-0" id="inlineFormCustomSelect">
                      <option value="">Select category</option>
                      @foreach ($categories as $category)
                        <optgroup label="{{ $category->name }}">
                          @foreach($category->subcategories as $sub)
                              <option value="{{ $sub->id }}">{{ $sub->name }}</option>
                          @endforeach
                        </optgroup>
                      @endforeach
              </select>

我尝试了很多更改并使用mu功能代码播放,但没有任何内容仍会返回no results!错误。

1 个答案:

答案 0 :(得分:1)

这应该可行

$ads = Ad::when($searchTitle, function ($query) use ($searchTitle) {
    return $query->where('title', 'like', '%'.$searchTitle.'%')
        ->orWhere('description', 'like', '%'.$searchTitle.'%');
})
->when($searchCategory, function ($query) use ($searchCategory) {
    return $query->whereHas('subcategory', function ($q) use ($searchCategory) {
        $q->where('id', $searchCategory);
    });
})
->when($searchLocation, function ($query) use ($searchLocation) {
    return $query->whereHas('location', function ($q) use ($searchLocation) {
        $q->where('id', $searchLocation);
    });
})
->paginate(10)
->appends(request()->query());
  

也不要忘记输入的名称..它应该与请求相对应。