Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

j2teamnnl's avatar

Asking an advise about Pivot Table

I have 3 tables like this

Student: id | name

class Student extends Model
{
    protected $table = 'students';

    public function marks () {
        return $this->belongsToMany( 'App\Models\Subject', 'marks' )->using( 'App\Models\Mark');
    }
}

Subject: id | name

class Subject extends Model
{
    protected $table = 'subjects';

    public function marks () {
        return $this->belongsToMany( 'App\Models\Student', 'marks' )->using( 'App\Models\Mark');
    }
}

Mark: subject_id| student_id| type_of_exam | times_taking_exam | mark

class Mark extends Pivot
{
    protected $table = 'marks';
    public function student() {
        return $this->belongsTo('App\Models\Student','student_id');
    }
    public function subject() {
        return $this->belongsTo('App\Models\Student','subject_id');
    }
    public $timestamps = false;
}

The table Mark which has 4 column primary key (id_subject, id_student, type_of_exam, times_taking_exam)

I don't know my design database is correct or not, but if it did, how can I use sync to update or insert mark for my student. Because I understand that the method sync is like this:

$student->marks()->sync([
	$subject_id => [
		'type_of_exam' => 1,
		'times_taking_exam' => 1,
		'mark' => 10,
	]
]);

But it is not correct for this situation cause it will run this code like this:

Mark::updateOrCreate( [
    'student_id' => $student_id,
    'subject_id'  => $subject_id,
], [
    'type_of_exam' => 1,
    'times_taking_exam' => 1,
    'mark' => 10
] );

Instead, I want this:

Mark::updateOrCreate( [
    'student_id' => $student_id,
    'subject_id' => $subject_id,
    'type_of_exam'  => 1,
    'times_taking_exam' => 1,
], [
    'mark' => 10
] );

I have tried use Mark as Model but I think it's not the best way.

0 likes
2 replies
SilenceBringer's avatar

Hi @j2teamnnl I don't think it's possible to update mark as pivot table in your case, because you have complex key, and built-in pivot tables doesn't support it. So, using of Mark as a model for updating is correct way here

1 like
j2teamnnl's avatar

Thank you for your quickly reply. If there isn't any other options, I guess that is the best answer at the moment.

Please or to participate in this conversation.