vendredi 17 février 2017

How do I match an array against Eloquent-Relationship via logical AND? Laravel 5.1

Imagine there is a Table with some posts which hasMany(tags), which in reverse belongsTo(posts). The tags-Table contains

id, post_id, tag
 1,      42, Foo
 2,      42, Bar
 3,      53, Bar
 4,      53, Baz
 5,      64, Bar

Then there is an array

$array = ['Bar','Baz','Qux']

How do I get the posts, for which all tags are in $array?
In this example, the result should contain the posts [53,64], but not 42, because Foo is not in $array.

In other words: how do I make a logical AND through Eloquent? A logical OR is no problem, e.g.:

Posts::with('tags')
->whereHas('tags', function($q) {
    $q->whereIn('tag', $array);
})
->get();

But this also returns post 42, as it has the tag Bar.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire