Ошибка «Call to undefined relationship» в Laravel

Рейтинг: 0Ответов: 0Опубликовано: 22.06.2023

Недавно начал изучать Laravel и решил его использовать для своего учебного проекта в колледже - АИС для составления расписания занятий.

Я создал метод в контроллере:

public function show(Request $request){
    if (($request->get('group') == null) || ($request->get('date') == null)){
        return view("timetable.show", ['groups' => Group::all()]);
    }
    else {
        $timetable = new Timetable();
        $dayTimetable = $timetable
            ->with('schedules')
            ->with('subjects')
            ->with('teachers')
            ->with('classesTypes')
            ->with('classrooms')
            ->whereGroup($request->get('group'))
            ->where('date', '=', $request->get('date'))
            ->get();
        return view('timetable.show', ['timetable' => $dayTimetable]);
    }
}

В модели создал соответствующие отношения:

class Timetable extends Model
{
    public function schedules(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Schedule::class, 'classes_number');
    }

    public function subjects(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Subject::class, 'subject');
    }

    public function teachers(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Teacher::class, 'teacher');
    }

    public function classesTypes(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(ClassesType::class, 'classes_type');
    }

    public function classrooms(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Classroom::class, 'classroom');
    }
}

При вызове метода из контроллера возникает ошибка: Call to undefined relationship [schedules] on model [App\Models\Timetable].

Вот миграции для данных таблиц (сгенерированы автоматически):
schedules:

public function up()
{
    Schema::create('schedules', function (Blueprint $table) {
        $table->integer('id', true);
        $table->integer('classes_number')->comment('Номер пары');
        $table->time('start_time')->comment('Время начала');
        $table->time('end_time')->comment('Время окончания');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('schedules');
}

timetables

public function up()
{
    Schema::create('timetables', function (Blueprint $table) {
        $table->integer('id', true);
        $table->date('date')->comment('Дата');
        $table->integer('classes_number')->index('classes_number')->comment('Номер пары');
        $table->integer('group')->index('group')->comment('Группа');
        $table->integer('subject')->index('subject')->comment('Дисциплина');
        $table->integer('classes_type')->index('classes_type')->comment('Вид занятия (пары)');
        $table->integer('classroom')->index('classroom')->comment('Аудитория');
        $table->timestamps();
        $table->integer('teacher')->nullable()->index('timetables_teachers_id_fk');
    });
}

public function down()
{
    Schema::dropIfExists('timetables');
}

Внешние ключи для timetables

public function up()
{
    Schema::table('timetables', function (Blueprint $table) {
        $table->foreign(['classes_number'], 'timetables_ibfk_2')->references(['id'])->on('schedules');
        $table->foreign(['classroom'], 'timetables_ibfk_4')->references(['id'])->on('classroom_types');
        $table->foreign(['teacher'], 'timetables_teachers_id_fk')->references(['id'])->on('teachers');
        $table->foreign(['subject'], 'timetables_ibfk_1')->references(['id'])->on('subjects');
        $table->foreign(['group'], 'timetables_ibfk_3')->references(['id'])->on('groups');
        $table->foreign(['classes_type'], 'timetables_ibfk_5')->references(['id'])->on('classes_types');
    });
}

Если убрать ->with('schedules'), то всё работает. Попробовал имя функции скопировать, чтобы исключить неправильное написание, но не помогло. Подскажите, в чём может быть проблема?

Ответы

Ответов пока нет.