我想获取所有产品并从类别表中获取每个产品类别的名称..任何人都可以帮助???
public function viewProducts(Request $request){
$products = Product::get();
foreach($products as $key => $val){
$category_name = Category::where(['id' => $val- >category_id])->first();
$products[$key]->category_name = $category_name->name;
}
$products = json_decode(json_encode($products));
//echo "<pre>"; print_r($products); die;
return view('admin.products.view_products')->with(compact('products'));
}
答案 0 :(得分:1)
您可以使用加入
$products = Product::join('categories','categories.id', 'products.category_id')->get();