Support the ongoing development of Laravel.io →
Requests Database Eloquent

I am providing an example

there are two tables paper and question in paper table {id, name} in question table {id, name, score} in pivot paper_question table {id, paper_id, question_id, question_score}

how to define this belongsToMany relationship in model with "withPivot" or something else. how to use sync method to parse question id and score together?

Last updated 3 years ago.
0

I thinks its already clear in the documentation, but here are the headlines

	
// Paper.php model
public function questions()
{
	return $this->belongsToMany('App\Question')->withPivot('question_score');
}

// Question.php model
public function papers()
{
	return $this->belongsToMany('App\Paper')->withPivot('question_score');
}

// anywhere in controllers

// update paper's questions
$paper->questions()->sync([
	$question_1_id => ['question_score' => 'your_value'],
	$question_2_id => ['question_score' => 'your_value'],
]); // assuming that: $paper is valid instance, $question_1_id & $question_2_id are valid ids

// update question's papers
$question->papers()->sync([
	$paper_1_id => ['question_score' => 'your_value'],
	$paper_2_id => ['question_score' => 'your_value'],
]);

Hope it helps.

farshidgh70 liked this reply

1

just assume I have an array where array keys are question_id and array values are question_scores how can I parse it in sync method for updating the pivot table.

0
// question with id 1 has a question_score 100.
$data = array(1 => 100);
$syncData = array();
foreach($data as $id => $score){
$syncData[$id] = array('question_score' => $score);
}
$paper->questions()->sync($syncData);
Last updated 10 years ago.

farshidgh70 liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

alvi1987 alvi1987 Joined 20 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.