如何在Laravel中加入?只获取另一个表的一些列

时间:2019-07-04 07:07:06

标签: laravel laravel-5 join eloquent

我正在管理面板上……我从数据库中获取所有产品并在表中显示……问题是我想从“类别”表中获取每种产品类别,并从“产品”中获取每种产品的库存属性”表...我正在创建一个联接,但是此联接折叠了另一个表中的产品ID,名称股票或奖品...谢谢。

  public function viewProducts(Request $request){
    $products = Product::get();

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

    $products = json_decode(json_encode($products));

    //echo "<pre>"; print_r($products); die;

    return view('admin.products.view_products')->with(compact('products'));
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

Product::join('categories','categories.id','products.category_id')
->join('products_attributes','products_attributes.product_id','products.id')
->select(['categories.category_name as category_name', 'products_attributes.stock as product_stock', 'products.*'])
->get()->toArray();

答案 1 :(得分:0)

$products = Product::join('categories','categories.id','products.category_id')
->join('products_attributes','products_attributes.product_id','products.id')
->get(['categories.category_name as category_name', 'products_attributes.stock as product_stock', 'products.*']);