Laravel get a collection of relationship items

后端 未结 4 1074
难免孤独
难免孤独 2021-01-07 18:01

I\'m stuck on this what seems like a simple task.

I have a User that has many Shops that have many Products..

I\'m trying to get all the Pr

4条回答
  •  -上瘾入骨i
    2021-01-07 18:25

    In this case you can use lazy eager loading:

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

    To iterate over products:

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

    If you need just products:

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

    In both cases, you'll have the same number of queries to DB, so I'd use the first example in a real app.

提交回复
热议问题