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

KIEYCH's avatar

Can you help me figure out this relationship? Probably ez

I have these tables: quiz (id,name,etc) quiz_questions (id,name,etc) quiz_associated_questions (quiz_id,question_id)

on my Quiz model:

public function questions(){ // helppppppp ? I've tried belongs to many App\QuizQuestion, but no worrrk xD }

0 likes
10 replies
KIEYCH's avatar

I would need a Quiz model, QuizQuestion model, correct? Or could I use only a Quiz model?

Snapey's avatar

do you need many to many?

assuming so, then since you don't follow conventions with the name of the pivot table then you need to specify it in your hasMany relationship

just check the docs

1 like
KIEYCH's avatar

Just figured it out: return $this->belongsToMany('App\QuizQuestion','quiz_associated_questions','quiz_id','question_id');

Sorry... @Snapey What would be the convention names for this? What would you use instead of:

quiz, quiz_questions, quiz_associated_questions ?

Questions can belong to many Quiz A quiz can have many questions

I also have, quiz_answers Which belongs to One quiz_question

Snapey's avatar

so to clarify the last message in response to your post.

if one quiz has a set of questions but questions belong to a single quiz then you don't need a pivot table

just put a quiz_id column on the question

1 like
Snapey's avatar

last post overlapped yours

convention is that the pivot is named after the two tables in alphabetical order

so if you have quiz and questions as tables, the pivot would be questions_quiz

any other choice is possible but it's not automatic - you have to advise eloquent

1 like
KIEYCH's avatar

@Snapey The thing is I want the questions to be re-usable by other quizzes , this is why I've done it this way, is it correct?

For example, a user may create a Quiz, and add existing questions or create new ones for the quiz... but for example, the quiz_answers can only belong to one quiz_questions correct? Wouldn't make sense to do the same for the quiz_answers since I use a table "quiz_answered_questions" (answer_id,user_id)

KIEYCH's avatar

Would it make sense to make answers re-usable? How would I track the users answers then?

KIEYCH's avatar

Forget it I'm just confused, I think I can do the same for the answers...Thanks anyway, the creation of this thread helped me clear my head LOL

Snapey's avatar

why is the correct answer not stored with the question(or did I misunderstand) ?

If a quiz has many questions and a question can belong to many quiz then, yes, you need a pivot table which has the id for each table

KIEYCH's avatar

Yes that's exactly it @Snapey I should store the correct answer together with the question and quiz (quiz_answered_questions = quiz_id, question_id, answer_id )... what a mess xD

Please or to participate in this conversation.