Laravel eloquent gets all records where all ids are in many ways

I have a table Posts

, it has three fields id

, title

, description

.

My Post

Model

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'description'];

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag');
    }
}

      

My Tag

Model

class Tag extends Model
{
    use SoftDeletes;

    protected $fillable = ['name'];

    public function posts()
    {
        return $this->belongsToMany(Post::class, 'post_tag');
    }
}

      

Now I want to receive messages and paginate where I have a tag filter, for example I have two tags animals

and news

that have id 1

and 2

. Now I want to get all messages with tags 1

and 2

and paginate

. Here is what I tried

        Post:: with('tags')->whereHas('tags', function($q) {
            $q->whereIn('id', [1, 2]);
        })->paginate();

      

But this is how I whereIn

return messages with tags 1

or 2

or both

. But I want a post that has both id tags 1 and 2.

I am using Laravel 5.2

.

+2


source to share


3 answers


You will need to go through the list of IDs to add this condition. For example:



$query =  Post::with('tags');
foreach ($ids as $id) {
    $query->whereHas('tags', function($q) use ($id) {
        $q->where('id', $id);
    });
}
$query->paginate();

      

+2


source


I don't think there is a built-in method for this, but I would suggest putting a foreach loop inside the whereHas method just for the sake of neatness.



$query = Post::with('tags')->wherehas('tags', function ($q) use ($ids) {
    foreach ($ids as $id) {
        $q->where('id', $id);
    }
})->paginate(10);

      

0


source


I was looking for the same and inspired by fooobar.com/questions/2191336 / ... I ended up with this

Code:

Post:: with('tags')->whereHas('tags', function($q) {
    $idList = [1,2];
    $q->whereIn('id', $idList)
      ->havingRaw('COUNT(id) = ?', [count($idList)])
})->paginate();

      

Since I think I can use it in multiple places, I did it in a dash, which you can watch here . What if you included this trait in your Post class you could use like below.

Code:

Post::with('tags')->whereHasRelationIds('tags', [1,2])->paginate();

      

0


source







All Articles