Answer the question
In order to leave comments, you need to log in
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"...
Question [
1 => 'ФОЛВЛ'
2 => 'nnbslb'
]
Answer [
1 => 'KNKLLV'
2 => 'VNSDLVNS'
3 => 'nvslds'
4 => 'vdsnkvsl'
5 => 'nsldkvklsdv'
6 => 'vlskdnvkls'
7 => 'vlskdvklsd'
8 => 'vsdlvnklsd'
]
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]);
}
Answer the question
In order to leave comments, you need to log in
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.
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
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 questionAsk a Question
731 491 924 answers to any question