Laravel 具有多态性和多对多关系的HasManyThrough
在我的Laravel应用程序中,我有以下几类:Laravel 具有多态性和多对多关系的HasManyThrough,laravel,eloquent,many-to-many,has-many-through,Laravel,Eloquent,Many To Many,Has Many Through,在我的Laravel应用程序中,我有以下几类: class Product extends Model { public function extended() { return $this->morphTo(); } public function users { return $this->belongsToMany('App\User', 'products_users', 'product_id');
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');
}
}
我可以使用bar::find(1)->product->users
轻松获取bar对象的用户,也可以使用user::find(1)->products
获取用户的bar
如何获取属于特定foo的所有条的用户?也就是说,
Foo::find(1)->users
应该返回所有具有属于Foo的id为1的条的用户。它基本上是多态的和多对多的关系。试试这样:
public function users()
{
$Foo = static::with(['bars', 'bars.products', 'bars.product.users'])->get();
return collect(array_flatten(array_pluck($Foo, 'bars.*.product.users')));
}
这个应该对您有用(代码已经过测试,但不是针对与您的设置完全相同的结构)。第一行将返回通过关系进行深度嵌套的所有用户。第二行将拉出用户,将其展平为一个数组,然后将数组转换为一个集合。我为这样的情况创建了一个
HasManyThrough
关系:
安装后,您可以这样使用它:
public function users()
{
$Foo = static::with(['bars', 'bars.products', 'bars.product.users'])->get();
return collect(array_flatten(array_pluck($Foo, 'bars.*.product.users')));
}
类Foo扩展模型{
使用\Staudenmeir\elokenthasmanydeep\hassrelationships;
公共功能用户(){
返回$this->hasmanydep(
用户::类,
[Bar::class,Product::class,'products_users'],
[null,['extended_type','extended_id']]
);
}
}
这似乎包括与给定Foo无关的用户使用find
语句而不是get
语句,然后:$Foo=static::with(['bar','bar.products','bar.product.users'])->find($This->id)代码>(假设主键是id
)