Laravel get a collection of relationship items

后端 未结 4 1073
难免孤独
难免孤独 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条回答
  • 2021-01-07 18:13

    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;
    
    0 讨论(0)
  • 2021-01-07 18:19

    You can use this :

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

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 18:25

    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

    0 讨论(0)
提交回复
热议问题