2

I have 3 tables tests, questions, options.

As you can imagine

  1. a test has many questions
  2. a question belongs to a test
  3. a question has many options
  4. an option belongs to a question

These relations are set up in the models already.

I got the data from the front end in this form:

array:3 [
  "name" => "First Test"
  "preparation" => "First Test prep"
  "questions" => array:2 [
    0 => array:2 [
      "title" => "Some question"
      "options" => array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => "d"
      ]
    ]
    1 => array:2 [
      "title" => "Another question"
      "options" => array:4 [
        0 => "e"
        1 => "f"
        2 => "g"
        3 => "h"
      ]
    ]
  ]
]

This data perfectly represents these relationships. In fact if I were using a NoSql database I would simply store this in the database.

My question is "what is the best way to store all of this data at once while using eloquent in Laravel"?

Note: It is in the form of Laravel's collection.

2 Answers 2

1
 class Test extends Model {

    $table = 'tests';
    function questions(){
                return $this->hasMany(Question::class, 'test_id');
            }

 }

class Question extends Model {

    $table = 'questions';
    function answers(){
        return $this->hasMany(Answer::class, 'question_id');
            }

    function test(){
        return $this->belongsTo(Test::class, 'test_id');
    }

}

class Answer extends Model {

    $table = 'answers';

    function question(){
        return $this->belongsTo(Question::class, 'question_id');
    }

}

of course i showed only relations ,tables and foreign keys. you can add any additional data to your models.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to create a structure of model objects from given data. JMS Serializer is a great library to do that, and it has laravel integration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.