2016-09-28 3 views
0

Ich habe zwei Tabellen: product, product_namesWie benutze ich Join in Laravel?

Product Product_names 
id  id | name | language | objectId 

I Funktion names() in Modell, das von key: id = objectId

diese beide Tabelle verbindet, wenn ich Anfrage tun wie zum Beispiel:

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

ich Sammlung mit Objekt aus Tabelle Product und getrennte Coelection mit names()

Wie kann ich diese Fusion in einer Sammlung führen?

Also, ich brauche etwas zu bekommen, wie:

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

Ohne ::with("Product_names")

Antwort

0

Zum Beispiel mit:

product.php Modell

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

in ProductController.php

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

in product.blade.php

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

Hoffentlich wird dies Ihr Problem lösen

+0

Woher hast du 'Post'? – Babaev

+1

Warum kann ich nicht einfach verwenden: '$ subcategories = Produkt :: mit (" productNames ") -> get();'? – Babaev

+0

Post dies ist ein Fehler, korrigiert. Ich habe alle Details geschrieben. –

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

Lust, deinen Code auszuarbeiten? –

0

Sie können Laravel des Query Builder (https://laravel.com/docs/5.3/queries#joins)

Für Ihre Frage verwenden, hier ist:

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