Laravel get a collection of relationship items

我怕爱的太早我们不能终老 提交于 2019-12-10 02:32:08

问题


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 Products for a certain User.

This is working, and is returning the Shops with their Products

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

But I need a Collection of only the Products. I tried the following but it's messing up the Query

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

Any idea what I'm doing wrong? Thank you!


回答1:


You can use this :

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

if you don't want replicate, you can use ->unique()




回答2:


what you need is a relationship between the User Model and the Product Model ..

this is possible using hasManyThrough relationship ..

USER MODEL

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

now, you can access all the user's products with

Auth::user()->products;



回答3:


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.




回答4:


Assuming that your product model has the shop id stored, try the following:

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

It will retrieve a collection of products that belong to the list of shops which belong to the authenticated user



来源:https://stackoverflow.com/questions/43909607/laravel-get-a-collection-of-relationship-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!