2016-12-27 16 views
2

マイProductcategory.phpがLaravel雄弁

public function products() 
{ 
    return $this->hasMany('App\Models\Product'); 
} 

を持っており、Product.phpが

public function productcategory() 
{ 
    return $this->belongsTo('App\Models\Productcategory', 'category_id'); 
} 

今私のルートは

Route::get('gallery/{slug}', '[email protected]'); 

ありましたURLがgallery/print-pattern-client-workの場合、同じカテゴリのすべての商品をどのように入手できますか?私は以下を持っていますが、category_idは整数で、スラグではありません。だから私はそれをどうやって行うかについてはあまりよく分かりません。

public function index() 
{ 
    $categoryslug = Request::segment(2); 
    $products = Productcategory::with('products')->where('category_id',$categoryslug)->get(); 
... 
} 
+0

'print-pattern-client-work'それはどのカテゴリですか? –

答えて

2

これは、あなたのproduct_categoriesテーブルに "スラッグ" という名前の列を前提としています。あなたの記述された関係はうまくいく。

あなたが
public function scopeFindByCategorySlug($query, $categorySlug) 
{ 
    return $query->whereHas('productcategory', function ($query) use ($categorySlug) { 
     $query->where('slug', $categorySlug); 
    }); 
} 

Product.php

にアクセサを作ることができる

は、その後、あなたのコントローラには、これを呼び出す:

public function index(Request $request, $slug) 
{ 
    $products = Product::findByCategorySlug($slug)->get(); 
} 

編集:

コメントで述べたように実際の必要はありませんアクセサのために。これは基本的に、あなたが(コントローラに)必要なすべてのです:あなたはLaravelを使用している

public function index(Request $request, $slug) 
{ 
    $products = Product::whereHas('productcategory', function ($query) use ($categorySlug) { 
     $query->where('slug', $categorySlug); 
    })->get(); 
} 
+1

彼は 'index'メソッドで' whereHas'を直接行うこともできますが、あなたの答えは本当に唯一正しいものです。 – AntoineB

+0

ありがとう、これは働いた。 $ product = Product :: whereHas( 'productcategory'、function($ query))($ slug){ $ query-> where( 'slug'、$ slug); })> get(); – shin

1

使用$slugない

$categoryslug = Request::segment(2); 

を行い

public function index($slug) 
{ 
    $products = Productcategory::with('products')->where('category_id',$slug)->get(); 
... 
} 
-1

として、あなたはLaravelのMany to Many Relationships次のようなを使用する必要があります。

あなたのテーブル構造は以下のようになります:

- products 
    - id 
    - name 
    - ... 

- categories 
    - id 
    - name 
    - slug 
    - ... 

- category_product 
    - id 
    - category_id 
    - product_id 
    - ... 

あなたのモデルは次のようになります:

class Product extends Model { 

    public function categories() { 
     $this->belongsToMany(Category::class, 'category_product'); 
    } 

} 

class Category extends Model { 

    public function products() { 
     $this->belongsToMany(Product::class, 'category_product'); 
    } 

} 

あなたはすべての製品を取得できますこのような特定の$category_slugのために:sは

$category = Category::where('slug', $category_slug)->first(); 
if($category) { 
    $products = $category->products; 
}