Я решил проблему, не используя отношения многие ко многим, но используя один ко многим. Таблицы AllowedDpartments и AvailableHours получают свои собственные модели.
Модель Отдела имеет много Разрешенных документов, но у Разрешенного отдела есть только один Отдел. То же самое относится к классам и доступным часам, дням и доступным часам и, наконец, доступным часам и разрешенным отделам. Это приводит к следующим отношениям:
class Day extends Model{
protected $guarded=[];
public function availableHours(){
return $this->hasMany(AvailableHour::class);
}
}
.
class Classroom extends Model{
public function availableHours()
{
//relationship with availableHour which determines the available hours
return $this->hasMany(AvailableHour::class);
}
}
.
class AvailableHour extends Model{
//get room this hour belongs to
public function classroom() {
return $this->belongsTo(Classroom::class,'number');
}
//get the day this hour belongs to
public function day(){
return $this->belongsTo(Day::class);
}
//get all the allowedDepartments for this hour
public function allowedDepartments(){
return $this->hasMany(AllowedDepartment::class);
}
}
.
class AllowedDepartment extends Model
{
//get the availableHour this AllowedDepartment belongs to
public function availableHour(){
return $this->belongsTo(AvailableHour::class);
}
// get the department this AllowedDepartment belongs to
public function department(){
return $this->belongsTo(Department::class);
}
}
.
class Department extends Model{
//get all the allowedDepartments this Department has
public function allowedDepartments(){
return $this->hasMany(AllowedDepartment::class);
}
}
Следующий запрос возвращает классные комнаты, доступные для отдела в $department
.
$classrooms=Classroom::whereHas('AvailableHours.AllowedDepartments.Department',function(Builder $query) use ($department){
$query->where('id',$department->id);
})->get('number')`