Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HasManyThrough with polymorphic and many-to-many relations

In my Laravel application I have the following classes:

class Product extends Model
{
    public function extended()
    {
        return $this->morphTo();
    }

    public function users {
        return $this->belongsToMany('App\User', 'products_users', 'product_id');
    }
}

class Foo extends Model 
{
    public function product()
    {
        return $this->morphOne('App\Product', 'extended');
    }
    public function bars()
    {
        return $this->hasMany('App\Bar');
    }
}

class Bar extends Model 
{
    public function product()
    {
        return $this->morphOne('App\Product', 'extended');
    }

    public function foo()
    {
        return $this->belongsTo('App\Foo');
    }
}

class User extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product', 'products_users', 'user_id');
    }
}

I can easily get users of a bar object using Bar::find(1)->product->users and I can also get the bars of a user with User::find(1)->products.

How can I get the users of all bars belonging to a specific foo? That is, Foo::find(1)->users should return all users that have the bars belonging to Foo with id 1. It's basically hasManyThrough with polymorphic and many-to-many relations.

like image 888
Oskar Persson Avatar asked Apr 14 '16 18:04

Oskar Persson


Video Answer


1 Answers

I created a HasManyThrough relationship for cases like this: Repository on GitHub

After the installation, you can use it like this:

class Foo extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function users() {
        return $this->hasManyDeep(
            User::class,
            [Bar::class, Product::class, 'products_users'],
            [null, ['extended_type', 'extended_id']]
        );
    }
}
like image 168
Jonas Staudenmeir Avatar answered Jan 04 '23 05:01

Jonas Staudenmeir