Thursday, March 16, 2017

Eloquent hasManyThrough with belongsTo on intermediate model

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');
    }
}



via Emin

Advertisement