Laravel gets a set of relationship items

I am stuck with this, which seems like a simple task.

I have a User who has many stores that have many products.

I am trying to get all Products for a specific User.

It works and returns stores with their products.

\Auth::user()->shops()->with('products')->get();

But I only need a collection of products. I tried the following, but it messed up the request

\Auth::user()->shops()->with('products')->select('products.*')->get();

Any idea what I'm doing wrong? Thank!

+4
source share
4 answers

you need a relationship between the user model and the product model.

this is possible using a relationship hasManyThrough.

USER MODEL

public function products()
{
    return $this->hasManyThrough('App\Product', 'App\Shop')
}

you can now access all custom products with

Auth::user()->products;
+7

:

\Auth::user()->shops()->with('products')->get()->pluck('products')->flatten();

, ->unique()

+4

In this case, you can use lazy loading :

auth()->user()->load('shops.products');

To sort through products:

@foreach (auth()->user()->shops as $shop)
    @foreach ($shop->products as $product)
        {{ $product->name }}
    @endforeach
@endforeach

If you only need products:

Product::whereHas('shop', function ($q) {
    $q->where('user_id', auth()->id());
})->get();

In both cases, you will have the same number of database queries, so I would use the first example in a real application.

0
source

Assuming that your store model is stored in your product model, try the following:

Products::whereIn('id_shop',
    Shops::select('id')
    ->where('id_owner_user',Auth::user()->id)
    ->get())
->get()

He will receive a collection of products belonging to the list of stores belonging to the authenticated user.

-2
source

Source: https://habr.com/ru/post/1676893/


All Articles