M
M
maiskiykot2020-11-27 18:23:39
Laravel
maiskiykot, 2020-11-27 18:23:39

How to make a selection in a controller using pivot?

There is a table posts
id
post
----
post_categories
id
Category
---
pivot post_post_category
post_id
post_category_id

Everything works - creating, editing, deleting through models. I can not achieve a selection by post_category_id. I copied and pasted this request:

Post::with(['postCategories' => function($query) {
                  $query->wherePivot('post_category_id',$this->page);
    }])->get();

But it stupidly selects all posts without filtering by post_category_id. What did I miss? Thanks to all!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
maiskiykot, 2020-11-27
@maiskiykot

Normal heroes always go around:

Post::with('postCategories')->whereHas('postCategories', function($q) {
                       $q->where('post_category_id','=',$this->page); 
                   })
                   ->orderBy('created_at', 'desc')
                   ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question