返回Laravel的所有孙子
在我的模型中,我有这些关系:
- 类别 - >子类别:Hasmany
- 子类别 - >类别:属于
- 子类别 - >产品:Hasmany
- 产品 - >子类别:属于
- 类别 - >产品:HasmanyThrough
我想通过子类别表显示类别的所有产品。
因此,我写了此代码,但是我在DD($产品)上有问题,因为只有一种产品。
您能帮我在我的代码中解决问题吗?
public function show(Category $category)
{
$subcategories = Subcategory::join('categories','subcategories.category_id','categories.id')
->where('subcategories.category_id',$category->id)
->select('subcategories.id')
->get();
// DD($子类别);给我3个不同的子类别 - > ok
foreach ($subcategories as $subcategory) {
$query = Product::where('products.subcategory_id',$subcategory->id)->get();
}
$products = $query;
// dd($ products);只给我1个产品(实际上,有4种产品) - >诺
$data = [
'title'=> $description = $category->title,
'description'=> $description,
'heading'=> config('app.name'),
'category'=>$category,
'subcategory'=>$subcategories,
'products'=>$products,
];
// dd($data);
return view('category.show', $data)->with('products', $products);
in my models, I have those relations:
- Category -> Subcategories : hasMany
- Subcategories -> Category : belongsTo
- Subcategory -> Products : hasMany
- Products -> Subcategory : belongsTo
- Category -> Products : hasManyThrough
I want to display all the products of a category through the subcategory table.
So, I wrote this code, but I have a problem at the dd($products), because only one products is got.
Could you please help me to fix the issue in my code ?
public function show(Category $category)
{
$subcategories = Subcategory::join('categories','subcategories.category_id','categories.id')
->where('subcategories.category_id',$category->id)
->select('subcategories.id')
->get();
// dd($subcategories); give 3 different subcategories to me -> OK
foreach ($subcategories as $subcategory) {
$query = Product::where('products.subcategory_id',$subcategory->id)->get();
}
$products = $query;
// dd($products); give only 1 product to me (in fact, there are 4 products) -> NOK
$data = [
'title'=> $description = $category->title,
'description'=> $description,
'heading'=> config('app.name'),
'category'=>$category,
'subcategory'=>$subcategories,
'products'=>$products,
];
// dd($data);
return view('category.show', $data)->with('products', $products);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您只是在重新计算$ Query变量,而不是将其视为数组,这就是为什么只是带一个数组:
It seems you are just redeclaring the $query variable instead of treating it as an array, that's why is just bringing one: