2017-03-16 33 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

相关问题