@martinbean
Thank you for your reply. However, I want to ask how to implement to Eloquent Model not Database Relation. Ok, let's change lesson to course, but I don't want to add Examination.
I already have solution for this, but I don't know if it's right and I have a little problem too.
Course Model
class Course extends Model {
public function teachers()
{
return $this->belongsToMany('App\Teacher');
}
public function students()
{
return $this->belongsToMany('App\Student', 'course_student', 'course_id', 'student_id')->withPivot('id');
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Student) {
return new CourseStudent($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
Student Model
class Student extends Model {
public function courses()
{
return $this->belongsToMany('App\Course', 'course_student', 'student_id', 'course_id')->withPivot('id');
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Course) {
return new CourseStudent($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
Teacher Model
class Teacher extends Model {
public function courses()
{
return $this->belongsToMany('App\Course');
}
}
CourseStudent Pivot
class CourseStudent extends Pivot {
protected $table = 'course_student';
public function scores()
{
return $this->hasMany('App\Score', 'course_student_id');
}
}
When I try to get Score from Student, it's work. But if I try to get Student from Score, I get an error.
$student->courses()->first()->pivot->scores(); // it work.
$score->course(); // Error
Argument 1 passed to Illuminate\Database\Eloquent\Relations\Pivot::__construct() must be an instance of Illuminate\Database\Eloquent\Model, none given, called in F:\pindah\laravel\course\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 809 and defined
Maybe I have to create another model that implemet CourseStudent for Scores to get the right relation. Is it right like this?