Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 拉威尔搜索关系在哪里_Laravel_Search - Fatal编程技术网

Laravel 拉威尔搜索关系在哪里

Laravel 拉威尔搜索关系在哪里,laravel,search,Laravel,Search,我正在尝试对产品进行搜索,但它不会返回任何结果。我怀疑这和whereHas函数有关,但我就是搞不清楚。这是我的密码: 我的亲属: 类别模型: class Categories extends Eloquent { public function product() { return $this->hasMany('Products')->orderBy('name'); } } 产品型号: class Products extends El

我正在尝试对产品进行搜索,但它不会返回任何结果。我怀疑这和whereHas函数有关,但我就是搞不清楚。这是我的密码:

我的亲属:

类别模型:

class Categories extends Eloquent {

    public function product()
    {
        return $this->hasMany('Products')->orderBy('name');
    }
}
产品型号:

class Products extends Eloquent {

    public function category()
    {
        return $this->belongsTo('Category')->orderBy('name');
    }
}
我的搜索功能:

public function search()
{
    $search         = Input::get('search');

    $result             = Products::where('name', 'LIKE', '%'. $search .'%')->get();

    if ($result->first()) {

        return View::make('groceries.index')
        ->with('categories', Categories::with('product')->orderBy('name', 'asc')
        ->whereHas('product', function($query) use ($search)
        {
            $query->where('name', 'LIKE', '%'.$search.'%');
        }));
    }
}
他认为:

@foreach ($categories as $category)

//do stuff

    @foreach ($category->product as $products)

//Show results

    @endforeach

@endforeach
您必须调用
get()
来获取数据。 我认为这将是更可读的代码

public function search()
{
    $search         = Input::get('search');
    $result         = Products::where('name', 'LIKE', '%'. $search .'%')->get();

    if ($result->first()) {
        $categories = Categories::with('product')->orderBy('name', 'asc')
                                 ->whereHas('product', function($query) use ($search){
                                        $query->where('name', 'LIKE', '%'.$search.'%');
                                  })->get();
        return View::make('groceries.index')
                   ->with('categories', $categories);
    }
}
谢谢,忘了拿礼物了真的…:)令人惊叹的!