H
H
hollanditkzn2018-02-06 16:33:55
Yii
hollanditkzn, 2018-02-06 16:33:55

How to save in the database, by selection and bind an object to json?

The question may not be clear, but I have the creation of tests, there is 1 question and 4 possible answers. It does not matter how many questions the user created, the main thing is 4 answers. It was easy to get the questions out, but getting the answers so that every 4 answers are tied to one question became more difficult for me. And I need to send them to the database in json format, that is, do them json_encode to get this line

{"0": "Ответ 5", "1":"Ответ 6", "2":"Ответ 7", "3"...

I get these days
Question	[
    1 => 'ФОЛВЛ'
    2 => 'nnbslb'
]
Answer	[
    1 => 'KNKLLV'
    2 => 'VNSDLVNS'
    3 => 'nvslds'
    4 => 'vdsnkvsl'
    5 => 'nsldkvklsdv'
    6 => 'vlskdnvkls'
    7 => 'vlskdvklsd'
    8 => 'vsdlvnklsd'
]

That is, there 1 question should contain up to 4, 2 question 4-8 answers.
I tried but I still can't figure out how to take them
public function actionCreate()
    {
        $model = new Questions();
        $request = Yii::$app->request;
        $question = $request->post('Question');
        $answer = $request->post('Answer');
        if ($question){
            foreach ($question as $value){
                $model->name = $question;
                foreach ($answer as $key => $item){
// Вот тут я не могу понять как сохранить такие данные и их правильно раскидать
                }
            }
        }
        return $this->render('create', ['model' => $model]);
    }

1 question and 4 answer options are stored in the database in the form (string json)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2018-02-06
@slo_nik

Good afternoon.
Use three tables, the first - questions, the second - answers, the third - binder, where the id of the question and answers will be stored.
In the models, create the appropriate relationships, in the database, create the primary keys.

M
Maxim Timofeev, 2018-02-06
@webinar

I do not quite understand what exactly is the problem?
convert array to json and back? Then there is
www.yiiframework.com/doc-2.0/yii-helpers-json.html
and functions built into php
php.net/manual/ru/function.json-encode.php
php.net/manual/ru/function. json-decode.php
well, in afterFind convert to json, and in beforeSave vice versa into an array

I
Igor Vasiliev, 2019-05-02
@Isolution666

In order not to say that I came up with this, just study the file:
https://github.com/samdark/yii2-cookbook/blob/mast...
I think now you can save information in different formats))
You can, of course, like Maxim Timofeev suggested, but after all, everything is ready, one line is enough, and the data is already in a different format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question