我正在用laravel建立一个网站。 我使用以下模型:
帖子可以有许多countrytags
,citytags
或categorytags
,反之亦然。
我想按标签搜索帖子。
我使用此功能:
public function blogsearchresults(Request $request)
{
$attributes=request()->validate([
'countrytag_id'=>'required_without_all:citytag_id,categorytag_id',
'citytag_id'=>'required_without_all:countrytag_id,categorytag_id',
'categorytag_id'=>'required_without_all:countrytag_id,citytag_id'
]);
$posts=Post::all();
if($request->has('countrytag_id')) {
$countryid=$attributes['countrytag_id'];
$posts =$posts->whereHas('countrytags', function ($query) use ($countryid){
$query->wherein('countrytag_id', $countryid);
});
}
if($request->has('citytag_id')) {
$cityid=$attributes['citytag_id'];
$posts=$posts->whereHas('citytags', function ($query2) use ($cityid){
$query2->wherein('citytag_id', $cityid);
});
}
if($request->has('categorytag_id')) {
$categoryid=$attributes['categorytag_id'];
$posts=$posts->whereHas('categorytags', function ($query3) use ($categoryid){
$query3->wherein('categorytag_id', $categoryid);
});
}
$posts=$posts->paginate();
return view('pages.blog.blogsearchresults', compact('posts'));
}
但我收到此错误:
Method Illuminate\Database\Eloquent\Collection::whereHas does not exist.
能帮我解决这个问题吗? 谢谢
答案 0 :(得分:0)
方法all()
返回一个集合,您不能在其上使用查询生成器方法。 (同样,当您查询构建时,也不需要一遍又一遍地分配$ posts值)
public function blogsearchresults(Request $request)
{
$attributes = request()->validate([
'countrytag_id'=>'required_without_all:citytag_id,categorytag_id',
'citytag_id'=>'required_without_all:countrytag_id,categorytag_id',
'categorytag_id'=>'required_without_all:countrytag_id,citytag_id'
]);
$postQuery = Post::query();
if($request->has('countrytag_id')) {
$countryid = $attributes['countrytag_id'];
$postQuery->whereHas('countrytags', function ($query) use ($countryid){
$query->wherein('countrytag_id', $countryid);
});
}
if($request->has('citytag_id')) {
$cityid = $attributes['citytag_id'];
$postQuery->whereHas('citytags', function ($query2) use ($cityid){
$query2->wherein('citytag_id', $cityid);
});
}
if($request->has('categorytag_id')) {
$categoryid = $attributes['categorytag_id'];
$postQuery->whereHas('categorytags', function ($query3) use ($categoryid){
$query3->wherein('categorytag_id', $categoryid);
});
}
$posts = $postQuery->paginate();
return view('pages.blog.blogsearchresults', compact('posts'));
}