Back

search with belongsTo and belongsToMany


murilolivorato posted 8 months ago

Hello Guys , I have a question . I have those tables -

Post PostCategory ( belongsTo Post ) PostTags ( belongsToMany Post )

And I want to -

Search those 
POSTS that has 
PostCategory  with id ( PostCategory  ID ) 1 and 2 and
PostTags with id ( PostTags  ID ) 2 and 3 

So I can do like this -

$post_category_ids = [1,2];
$post_tags_ids          = [2,3];

Post::select(['id', 'status' ,  'title' ,  'description' ])
            ->when($post_category_ids, function ($query) use ($post_category_ids) {
                return $query->whereIn('id' , $post_category_ids);
            })
         ->when($post_tags_ids          , function ($query) use ($post_tags_ids ) {
                          HOW COULD I DO IT WITH BELONGS TO MANY HERE ?
            })
    ->get()

thanks


Sign in to participate in this thread!



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