Have a look first at this image. How would you solve the problem, when you have two pivot tables? Or would you solve it differently?

To make it more understandable. We have three "normal" models (User, Course and Lesson) and two Pivot tables (enrollments should actually be called course_user but I changed the name so it is more clear and enrollment_lesson).
Have a look at my problem. I cannot use the relationship here:
use Illuminate\Database\Eloquent\Relations\Pivot;
class Enrollment extends Pivot
{
protected $guarded = [];
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = true;
public function lessons()
{
return $this->belongsToMany(Lesson::class, 'enrollment_lesson', 'enrollment_id', 'lesson_id')
->using(EnrollmentLesson::class)
->as('enrolledLesson')
->withTimestamps();
}
}
When I use it in phpunit:
$course->enrolledStudents()->first()->enrollment->lessons()->attach(1)
I get the error:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: enrollment_lesson.enrollment_id (SQL: insert into "enrollment_lesson" ("lesson_id", "enrollment_id", "created_at", "updated_at") values (1, ?, 2021-06-15 16:00:40, 2021-06-15 16:00:40))
Sorry about the image not having visible relationship arrows, but I think this should be clear. Thank you!