2017-03-16 35 views
0

我可以得到hasManyThrough關係工作正常,當中間模型有一個hasMany關係。但是如果中間模型與我的StoreProduct模型一樣有belongsTo?這對我來說應該是有用的,但它不會。Eloquent hasManyThrough與belongsTo在中間模型

我錯過了什麼?

我如何獲得所有產品的商店(通過「StoreProducts」)?

class Product extends Model 
{ 
    public function storeProducts() 
    { 
     return $this->hasMany('App\StoreProduct'); 
    } 

    public function stores() 
    { 
     return $this->hasManyThrough('App\Store', 'App\StoreProduct'); 
    } 
} 

class StoreProduct extends Model 
{ 
    public function store() 
    { 
     return $this->belongsTo('App\Store'); 
    } 
} 

class Store extends Model 
{ 
    public function storeProducts() 
    { 
     return $this->hasMany('App\StoreProduct'); 
    } 
} 

回答

1

這種關係類型不起作用。 HasManyThroughHasManyHasManyThroughBelongsTo關係不存在。你可以寫你自己來實現這一點,也可以反向工作(我相信是很容易)

public function stores() 
{ 
    return Store::whereHas('store_products', function(q){ 
     return $q->whereHas('product', function(q){ 
      return $q->where('id', $this->id); 
     }); 
    }); 
} 

此功能將取代一個在Products模型。

+1

其實我似乎已經通過使用StoreProduct作爲主軸在產品和商店之間創建ManyToMany關係來解決此問題。 在此處找到解決方案:https://laracasts.com/discuss/channels/eloquent/hasmanythrough-with-intermediate-belongsto – Emin

相關問題