Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0
class Post 
{
    public function getPostsByTagId($id)
   {
      return static::where('tag_id', $id)->get();
   }
}
Last updated 1 year ago.
0
$posts = Post::whereHas('tags', function($q)
{
 $tagsIDs = [5,17,22];
            $q->whereIn('id', $tagsIDs);

})->get();

return $posts;

Last updated 1 year ago.
0

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.

Last updated 1 year ago.
0

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();

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

bakicdj bakicdj Joined 6 Aug 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.