2017-03-16 3 views
0

hasManyThroughの関係は、中間モデルがhasManyの関係にあるときにうまく動作することができます。しかし、私のStoreProductモデルのように中間モデルのbelongsToがあればどうでしょうか?これは働くことができるはずですが、私は理解できません。中間モデルにbelongsToを持つManyThrough

私には何が欠けていますか?

また、「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の関係は存在しません。この機能は、お使いのProductsモデルの1を置き換えます(私ははるかに簡単であると信じている)

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

あなたはこれを達成するために、独自のを書くことができ、またはあなたが後方に作業することができます。

+1

実際には、StoreProductをピボットとして使用して、ProductとStoreの間にManyToMany関係を作成して解決したようです。 ここに解決策が見つかりました:https://laracasts.com/discuss/channels/eloquent/hasmanythrough-with-intermediate-belongsto – Emin

関連する問題