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.
1 Answers
Answers 1
Try something like this:
public function users() { $Foo = static::with(['bars', 'bars.products', 'bars.product.users'])->get(); return collect(array_flatten(array_pluck($Foo, 'bars.*.product.users'))); }
This should work for you (code has been tested, but not against the exact same structure as your setup). The first line will return all the users deeply nested through the relationships. The second line will pull out the users, flatten them into an array, then transform the array into a collection.
0 comments:
Post a Comment