2016-12-27 14 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是一個整數,而不是一個slu。。所以我不太確定如何去做。

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

'print-pattern-client-work'是它的任何類別嗎? –

回答

2

這裏假設你有一個在你的product_categories表命名爲 「塞」 一欄。而你所描述的關係運作良好。

你可以做一個訪問中Product.php

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

然後在您的控制器調用此:

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

編輯:

正如在評論中提到有沒有實際需要爲訪問者。這基本上是所有你需要(在控制器):

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

他也可以直接在'index'方法中做'whereHas',但你的答案確實是唯一正確的答案。 – AntoineB

+0

謝謝,這工作。 $ products = Product :: whereHas('productcategory',function($ query)use($ slug){query-> where('slug',$ slug); }) - > get(); – shin

1

不要

$categoryslug = Request::segment(2); 

使用$slug

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

當你使用Laravel,你應該使用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'); 
    } 

} 

,您可以獲取所有產品s對於特定的$category_slug是這樣的:

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