通过多态性的Laravel复杂关系

时间:2019-07-23 19:31:56

标签: laravel eloquent

我有以下使用Laravel 5.3的模型:

提供者:

// Provider model

$primaryKey = 'id'

public function activities()
{
    return $this->hasMany(Activity::class);
}

活动:

// Activity model

$primaryKey = 'id'

public function provider()
{
    return $this-belongsTo(Provider::class);
}

public function semesters()
{
    return $this->hasMany(Semester::class);
}

public function semesterPurchases()
{
    return $this->hasManyThrough(Purchase::class, Semester::class, 'activity_id', 'purchasable_id')
        ->where('purchasable_type', Semester::class);
}

学期:

// Semester model

$primaryKey = 'id'

public function activity()
{
    return $this->belongsTo(\App\Models\Activity::class, 'activity_id', 'id');
}

购买:

// Purchase model

$primaryKey = 'id'

public function purchasable()
{
    return $this->morphTo();
}

在我的情况下,Semester::classpurchasable_type。是否可以在Provider::classPurchase::class之间建立关系?为了使做这样的事情成为可能:

$providers = Provider::select('id', 'name', 'address')
  ->with('purchases')
  ->where('providers.id', 1)
  ->get();

我宁愿不参加这样的活动:

$providers = Provider::select('id', 'name', 'address')
  ->with('activities.purchases')
  ->where('providers.id', 1)
  ->get();

我知道我可以在hasManyThrough上使用Activity::class

1 个答案:

答案 0 :(得分:1)

Laravel不支持直接关系。

我已经为以下情况创建了一个程序包:https://github.com/staudenmeir/eloquent-has-many-deep

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

    public function purchases()
    {
        return $this->hasManyDeep(
            Purchase::class,
            [Activity::class, Semester::class],
            [null, null, ['purchasable_type', 'purchasable_id']]
        );
    }
}

Provider::find($id)->purchases;