Php 如何在Laravel 5.6中插入数组字段

Php 如何在Laravel 5.6中插入数组字段,php,eloquent,laravel-5.6,Php,Eloquent,Laravel 5.6,如何使用Laravel插入多个输入无线电数据 当我选择单选按钮并单击“提交表单”以插入数据库时 这是我的html: 问题不 对 不 1.你喜欢它的味道吗 2.你不喜欢这样 My QuestionController.php: $question = new Question; $question ->id = $request->get(id); $question ->question_no = 'question1'; $question ->score = $r

如何使用Laravel插入多个输入无线电数据

当我选择单选按钮并单击“提交表单”以插入数据库时

这是我的html:


问题不
对
不
1.你喜欢它的味道吗
2.你不喜欢这样
My QuestionController.php:

$question = new Question;
$question ->id = $request->get(id);
$question ->question_no = 'question1';
$question ->score = $request->get('q1');
$question ->save();
return redirect('/questionForm/create');
但它只能向数据库插入一行,我想像这样向数据库表插入数据:

|id|user_id|question_no|score|
|1 |  1    | question1 |  1  |
|2 |  1    | question2 |  0  |
    // deal with the q1 array
    $q1_array = $request->input('q1');
    $question = new Question;
    foreach ($q1_array as $q1_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q1_total =+ $q1_answer;
    }
    $question->question_no = 'question1';
    $question->score = $q1_total;
    $question->save();

    // now deal with the q2 array
    $q2_array = $request->input('q2');
    $question = new Question;
    foreach ($q2_array as $q2_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q2_total =+ $q2_answer;
    }
    $question->question_no = 'question2';
    $question->score = $q2_total;
    $question->save();

如何将多个数据插入数据库表?

多个数据意味着您必须插入多次
$request->get('q1')
$request->get('q2')
都会生成数组,因此您必须循环使用它们(或者
数组_sum()
,或者您需要执行的任何操作,以将q1/2值聚合到单个
分数
列)

现在,假设
score
是检查值的总和,并且
id
是一个自动递增列,它将如下所示:

|id|user_id|question_no|score|
|1 |  1    | question1 |  1  |
|2 |  1    | question2 |  0  |
    // deal with the q1 array
    $q1_array = $request->input('q1');
    $question = new Question;
    foreach ($q1_array as $q1_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q1_total =+ $q1_answer;
    }
    $question->question_no = 'question1';
    $question->score = $q1_total;
    $question->save();

    // now deal with the q2 array
    $q2_array = $request->input('q2');
    $question = new Question;
    foreach ($q2_array as $q2_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q2_total =+ $q2_answer;
    }
    $question->question_no = 'question2';
    $question->score = $q2_total;
    $question->save();
当然,这只是为了清楚起见。你可以在外面有一个单独的循环,这样你就不会重复问题1和问题2的代码

假设您的表名为
answers
,下面是一个更简短的版本:

    DB::table('answers')->insert([
        ['user_id' => $userId, 'question_no' => 'question1', 'score' => array_sum($request->input('q1'))],
        ['user_id' => $userId, 'question_no' => 'question2', 'score' => array_sum($request->input('q2'))],
    ]);

如何在标签中获取文本id?您有解决方案吗?哦,
标签中的数据在POST期间不会传递,所以您必须将它们放入
标签中。