【发布时间】:2019-07-31 03:24:19
【问题描述】:
我有以下使用 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::class 是purchasable_type。有没有办法在Provider::class 和Purchase::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();
我知道在Activity::class 上使用hasManyThrough 可以做到这一点
【问题讨论】: