我正在尝试搜索产品,但它不会返回任何结果。我怀疑它与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
答案 0 :(得分:1)
您必须致电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);
}
}