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

shahin_mahmud's avatar

HasManyThrough or ManyToMany Or What should i do for this purpose??

I have a quiz model, i want User to have Result for specific quiz. How should i make i migration and model relationship??

0 likes
5 replies
Lke's avatar

Hi,

I think it's similar to a User Role relationship, so a ManyToMany it's fine:

User side


class User extends Model
{
    public function quizzes()
    {
        return $this->belongsToMany('App\Quiz');
    }
}

Quiz side


class Quiz extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
} 

Note : Don't forget you need a pivot table.

Hope it helps.

Greetings.

Lke's avatar
Lke
Best Answer
Level 34

Hi,

Sorry i did not finish the answers , it's going to sound strange, but you might put the result on the pivot table.

if you think about it, it make sense, A result can exist only if we have a student that has participated in a quiz.

you are going to have something like this :

       user_id     | quizz_id     | result
       ------------|------------- | -------------

           1       |        2     |   20/20

           5       |         1    |   25/20

the only thing, that you need to sync your data so you don't have redundancy in your pivot table.

Greetings.

shahin_mahmud's avatar

Thanks for your help. I know how to access elements. Suppose i want to show a user average result do i have to

$total = 0; $counter = 0; foreach ($user->quizzes as $role) { $total += $role->pivot->result; $counter++; } $avg = $total / $counter; ?? or some better way?

Lke's avatar

Glade i could help,

i sometimes do something like this :

$avg = array_sum($values) / count($values);

it's up to you.

i prefer this approach because its less code, but also yours is fine.

Greetings.

Please or to participate in this conversation.