Skip to content
Advertisement

is there any way to validate if two compound index fields already exist in a many-to-many table?

For example here I am inserting the fields question_id, query_id, sub_test_id, test_id, score and answer. the question_id and query_id fields are unique index, how can I validate if when inserting these two fields they already exist in the table?

for ($i = 0; $i < $len; $i++) {
                $query->getQuestions()->attach($questions[$i]->id, [
                    'score' => $scores[$i], 'answer' => $answers[$i],
                    'sub_test_id' => $section->id, 'test_id' => $section->getTest->id
                ]);
            }

Advertisement

Answer

If I understand your question correctly, you are having some troubles when you are attaching something and the entry inside the pivot table already exists.

The solution is to use syncWithoutDetaching instead of attach.

syncWithotuDetaching uses a different syntax, take a look:

$query->getQuestions()->syncWithoutDetaching([
    $questions[$i]->id => [
        'score' => $scores[$i], 
        'answer' => $answers[$i],
        'sub_test_id' => $section->id, 
        'test_id' => $section->getTest->id
    ]
]);

If something is already there, nothing will change except the additional data (in your exemple, score would be updated).

If there is no link between your resources, it will be created.

You can think of syncWithoutDetaching as “update or create” for many to many relationships.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement