Many times it is necessary to obtain the records of a parent entity given the child in a many-to-many relationship; the typical relationship is that we have a many-to-many relationship between posts and tags and we want to obtain the posts that belong to certain tags; to do this, we can make a query like the following:
Post::whereHas('tags', function($q) {
$q->where('tag_id', 1);
})->whereHas('tags', function($q) {
$q->where('tag_id', 4);
})->get();
Or if the tags are dynamic:
$tag_ids=[25,40,30];
Post::where(function($query)use($tag_ids){
foreach ($id as $value){
$query->whereHas('tags',function ($query)use($value){
$query->where('tag_id',$value);
});
}
})->get();
The post model looks like:
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tags', 'post_id', 'tag_id');
}
}
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter