2016-09-28 69 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();