2016-08-21 32 views
1

我有這個表,hasManyThrough不工作

categories: id | name | slug 
Products: id | name | slug | category_id | brand_id 
Brands: id | name | slug | 

的問題,當我嘗試在功能的範疇帶到這裏出現的品牌。

分類模式

public function brands() 
{ 
    return $this->hasManyThrough('App\Brand', 'App\Product' 'brand_id', 'id'); 
} 

品牌要麼不出現或顯示在錯誤的類別。

是否有其他途徑可以通過品牌產品?

回答

0

變化如下的關係:

public function brands() 
{ 
    return $this->hasManyThrough('App\Brand', 'App\Product' 'category_id','id','brand_id'); 
} 

不過,我懷疑你可以使用hasManyThrough()檢索這種關係。
laravel site所示,您的表格應具有以下關係。

Category 1 * 1 Product * Brand
這是不可能的,你的情況。

我認爲你必須做手工,使用類似如下:

public function Brands($category_id){ 
    $products = Category::find($category_id)->Products()->get()->pluck('brand_id'); 
    $brands = Brands::whereIn('id','=',$products)->get(); 
    return $brands; 
} 
0

這是belongsToManyRelation

分類模式

public function brands() 
    { 
     return $this->belongsToMany('App\Brands', 'products', 'category_id', 'brand_id'); 
    }