我想从类别表中获取所有产品和每个产品的类别名称-Laravel

时间:2019-07-02 11:07:05

标签: laravel laravel-5 eloquent

我想获取所有产品并从类别表中获取每个产品类别的名称..任何人都可以帮助???

  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'));
}

1 个答案:

答案 0 :(得分:1)

您可以使用加入

$products = Product::join('categories','categories.id', 'products.category_id')->get();