2016-09-28 19 views
0

我有兩個表:product, product_names如何在Laravel中使用Join?

Product Product_names 
id  id | name | language | objectId 

我使用功能names()中,通過key: id = objectId

當我要求等作爲連接這兩個表型號:

$arr = Product::with("names")->get(); 

我得到收集與來自表Product的對象和與names()

如何將這個合併到一個收集結果中?

所以,我需要得到的東西如:

$oneResultObject = SELECT Product_names.name AS name from Product LEFT JOIN Product_names ON Product_names.objectId = Product.id; 

不使用::with("Product_names")

回答

0

例如:

product.php模型

class Product extends Model 
{ 
    protected $primaryKey = 'id'; 

    function productNames() { 
     return $this->hasOne('App\ProductName', 'id', 'objectId'); 
    } 

    public function show($id){ 
     self::with('productNames')->where('id', $id)->get(); 
    } 
} 
在ProductController.php

public function viewProduct($id, Product $products) 
    { 
     $product = $products->show($id); 
     return view('product', ['products' => $products]); 
    } 

在product.blade.php

<table> 
<tbody> 
@foreach ($products as $product) 
<tr> 
<th>{{ $product->id }}</th> 
<td>{{ $product->productNames->name }}</td> 
</tr> 
@endforeach 
</tbody> 
</table> 
</div> 

希望這將解決您的問題

+0

從哪裏得到'Post'? – Babaev

+1

爲什麼我不能使用簡單的:'$ subcategories = Product :: with(「productNames」) - > get();'? – Babaev

+0

發佈這是一個錯誤,更正。我寫了所有的細節。 –

0
$products = DB::table('product') 
     ->leftJoin('product_names', 'product.id', '=', 'product_names.objectId ') 
     ->get(); 
+0

介意詳細說明您的代碼? –

0

您可以使用Laravel的查詢生成器(https://laravel.com/docs/5.3/queries#joins

對於你的問題,在這裏是:

$prodcuts = DB::table('product') 
     ->leftJoin('product_names', 'product.id', '=', 'product_names.objectId ') 
     ->get();