1
votes

I can get the hasManyThrough relation to work fine when the intermediate model has a hasMany relation. But what about if the intermediate model has a belongsTo, like my StoreProduct model? It would make sense to me that this should be able to work, but it doesn't.

What am I missing?

And how would I get all the Product's Stores (through the "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

1 Answers

1
votes

This relationship type will not work. The HasManyThroughHasMany and HasManyThroughBelongsTo relationships do not exist. You could write your own to achieve this, or you can work backwards (which I believe is much easier)

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

This function would replace the one in your Products model.