i have blogs table in the DB which has tag,tag1,tag2 columns, i'm trying to get all the blogs related to current blog in the show page if any of the 3 tags are similar to it , i'm using the code below but the problem is that i'm getting the main blog with related which i don't want.
i'm using where not but its not working
function blogShow($id) {
$blog = Blog::find($id);
$tags = [$blog->tag,$blog->tag1,$blog->tag2];
$related = Blog::select("*")
->where('id', '!=', $id)
->whereIn('tag',$tags)
->orWhereIn('tag1',$tags)
->orWhereIn('tag2',$tags)
->get();
return view('main.blogs.show',compact('blog','related'));
}
PS: when i use -> toSql i'm getting the current query :
"select * from blogs
where id
!= ? and tag
in (?, ?, ?) or tag1
in (?, ?, ?) or tag2
in (?, ?, ?)"
which seems correct ,the $id value is correct as well so where is the problem .
My Answer:
>tag, $blog->tag1, $blog->tag2];__ $relatedBlogs = Blog::where('id', '!=', $id) ->where(function ($query) use ($tags) { foreach ($tags as $tag) { $query->orWhere('tag', 'like', '%' . $tag . '%') ->orWhere('tag1', 'like', '%' . $tag . '%') ->orWhere('tag2', 'like', '%' . $tag . '%'); } }) ->get();__ return view('blog.show', compact('blog', 'relatedBlogs')); }
Rate this post
5 of 5 based on 8834 votesComments