Laravel database many to many (Mysql) or keep Json in table

I need advice that I am using laravel and I'm not sure if I need a lot (mysql) or stay with Json that is encoded in a table (the rest of the code works fine), I hope I can explain it correctly. So here, the user has to solve an exam that has questions and the questions change when the button is clicked (each question is in one div, the content changes when clicked with jquery), so when clicked on the user it shows the question with 3 (for example) radio boxes as answers, of which one is correct. After the user selects the response form radio buttons and clicks next, their response (value) is saved in the session, and then the same div shows another question, and so on. Once the user gets to the last question,his responses are taken from the Session and sent by email. So now for the piece of code, Exam Table Structure.

   Schema::create('exams', function(Blueprint $table)
        {
        $table->increments('id');
                    $table->string('title')->unique();
                    $table->text('questions_json'); //json encode see example below
                    $table->integer('duration');
                    $table->string('remember_token',64);
                    $table->timestamps();
        });

      

'questions_json' looks like (this is an example)

[

   {
    "Question": "1+1?",
    "1": "11",
    "2": "2",
    "3": "-2",
    "correct": "2"
},
{
    "Question": "What is a rabbit?",
    "1": "Mammal",
    "2": "Vicious beast with sharp teeth",
    "3": "Cute thing",
    "correct": "1"
}

]

      

this is what I have now, so the controller reads this json text and deletes it correctly, and then sends the json to jquery with questions and answers, which then generate the form with radio buttons and the next button.

But with this "admin" will fail to edit once questions are asked (need to put id in json so it can), but the only time an admin would need to change this form is when they are wrong. So I'm not sure if I should leave it that way or change the db structure for many.

+3


source to share


1 answer


Storing JSON data in your database is (almost) never a good idea. For example, as you noticed, it gets tricky when you want to edit data.

I would suggest a scheme like this:

exams

  • name
  • Duration
  • remember_token

questions

  • text
  • exam_id

the answers

  • text
  • question_id
  • correct (logical)


Then define the following relationships :

Exam model

public function questions(){
    return $this->hasMany('Question');
}

      

Model question

public function answers(){
    return $this->hasMany('Answer');
}

public function exam(){
    return $this->belongsTo('Exam');
}

      

Response model

public function question(){
    return $this->belongsTo('Question');
}

      

More information on Relationships in Laravel Docs

+3


source







All Articles