Piotranon
Piotranon

Reputation: 11

Laravel Polymorphic One To Many Relationship

I would like to create a structure with models for exam app.

Basic models structure that i would imagine:

So I would like to have a structure like:

exam have many questions and to questions table, I want to add any type of model that extends my question Model which always contains 2 params ( 'question', 'max_points', and other fields specified for questions )

My current database structure

I want to add a relation between exams table and questions table, between questions table and closed_questions table and questions to open_questions.


So what I have tried:

I added relations for each question type to exams model morphedByMany(QuestionModelType::class,'questions') something like :

Exams.php //Model
    public function openQuestions()
    {
        return $this->morphedByMany(OpenQuestion::class, 'questions');
    }

    public function closedQuestions()
    {
        return $this->morphedByMany(ClosedQuestion::class, 'questions');
    }

I can operate on models but I don't think that's an ideal solution, or should I just leave it as it is. I think there is a nicer way of doing this, but I'm not familiar with this. Or should I just add a Relation that morphs over an array of all question types? How it should work when I would like to extend app with a new question type?

Upvotes: 1

Views: 430

Answers (1)

MANSOOR KOCHY
MANSOOR KOCHY

Reputation: 374

if you want to add condition relationship to Question you can try the below approach

Exam::with(['Question' => function(MorphTo $morphTo){
        $morphTo->morphWithCount([
            ModelOne::class => ['openQuestions' => function($query){
                $query->where('id',1);
            }],
            ModelTwo::class => ['closedQuestions']
        ]);
    }]);

in the above code, we check if the nested model polymorphic model is ModelOne catch the openQuestions or if the relationship is ModelTwo catch closedQuestions relationship, also you can assign your constraints to using the closure

Upvotes: 0

Related Questions