Laravel 合并为一个集合
我想从数据透视表中检索多条记录,包括一个表中的详细信息。目前,我必须为每个模型显示一个表,其中包含透视表中相应的行 这是我的控制器中的内容:Laravel 合并为一个集合,laravel,Laravel,我想从数据透视表中检索多条记录,包括一个表中的详细信息。目前,我必须为每个模型显示一个表,其中包含透视表中相应的行 这是我的控制器中的内容: $shops = Shop::where('user_id', auth()->user()->id)->with('products')->get(); return view('shop.pindex')->with('shops', $shops); 因此,我认为我必须具备以下条件: @foreach ($shops
$shops = Shop::where('user_id', auth()->user()->id)->with('products')->get();
return view('shop.pindex')->with('shops', $shops);
因此,我认为我必须具备以下条件:
@foreach ($shops as $shop)
{{$shop->name}}
@foreach($shop->products as $product)
Table
{{$product->pivot->qty}}
End Table
@endforeach
@endforeach
基本上,我只想要一个表,显示如下内容:
Shop Name | Product Name | SKU | qty
Shop A | Flask | AAA | 5
Shop A | Bottle | ABB | 6
Shop B | Flask | AAA | 15
然后使用连接查询,而不是加载关系
$shops = DB::table('shops as s')
->join('products as p', 's.id', '=', 'p.shop_id')
->where('s.user_id', auth()->user()->id)
->select(['s.name as shop_name','p.name as product_name','p.sku','p.qty'])
->get();