class Post
{
public function getPostsByTagId($id)
{
return static::where('tag_id', $id)->get();
}
}
$posts = Post::whereHas('tags', function($q)
{
$tagsIDs = [5,17,22];
$q->whereIn('id', $tagsIDs);
})->get();
return $posts;
johndavedecano said:
$posts = Post::whereHas('tags', function($q) { $tagsIDs = [5,17,22]; $q->whereIn('id', $tagsIDs); })->get(); return $posts;
This will return all posts that have ANY of these tag ids. I need posts that have EVERY tag listed in array, so by every tag, the list of returned post should be shorter.
I found the solution. If this can be done in better way, please let me know.
$tagIDs = [1,2,3];
$search = 'search string';
Post::where(function($q) use ($tagIDs, $search)
{
!$tagIDs ?: $q->whereIn('posts_tags.id_tag',$tagIDs)
->havingRaw('count(DISTINCT posts_tags.id_tag) = '. count($tagIDs));
!$search ?: $q->where('title', 'LIKE','%'.$search.'%');
})
->join('posts_tags','posts_tags.id_post, '=', 'post.id')
->groupBy('post.id')
->get()
->toArray();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community