J
J
jazzus2018-12-28 19:52:25
Laravel
jazzus, 2018-12-28 19:52:25

How to filter where in a With ManyToMany relationship?

I'm trying to make a request:

$products=Product::with(['lists' => function($query)
                        {
                            $query->where('user_id', Auth::id());
                        }]);

Lists - communicates with products through many to many. Gives an error message. Because intermediate table. And it returns a lot of products on one sheet (in an error, it tries to compare the product id with the product_id in the intermediate table). And it should return many sheets for each product (because as a result, a collection of products is formed). What is the best way to make a request of this kind? Like: give me all the products and for each product show me also with the lists that belong to the authorized user.
so that I end up doing $product->lists and get the lists of the authorized user in which there is a product

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2019-01-03
@jazzus

$products = Product::whereHas('lists', function ($query) {
    $query->where('user_id', Auth::id());
})->get();

Does this option not work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question