php Laravel 获取一组关系项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43909607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel get a collection of relationship items
提问by Miguel Stevens
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!
知道我做错了什么吗?谢谢!
回答by Mathieu Ferre
You can use this :
你可以使用这个:
\Auth::user()->shops()->with('products')->get()->pluck('products')->flatten();
if you don't want replicate, you can use ->unique()
如果你不想复制,你可以使用 ->unique()
回答by Demonyowh
what you need is a relationship between the User Model and the Product Model ..
您需要的是用户模型和产品模型之间的关系..
this is possible using hasManyThrough
relationship ..
这是可能的使用hasManyThrough
关系..
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;
回答by Alexey Mezenin
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.
在这两种情况下,您对 DB 的查询数量将相同,因此我将在实际应用程序中使用第一个示例。
回答by aaron0207
Assuming that your product model has the shop id stored, try the following:
假设您的产品型号存储了商店 ID,请尝试以下操作:
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
它将检索属于经过身份验证的用户的商店列表的产品集合