如何在Laravel中插入数组字段

时间:2018-08-07 13:46:17

标签: javascript laravel loops laravel-5

这是我的第二个主题

所以我试图用输入标签插入数组数据。 我用jquery来输入标签

<input type="button" class="btn btn-primary" onclick="steps(); return false;" value="Add  steps">

function steps() {
    var idf = document.getElementById("idf").value;
    var stre;
    stre="<p id='srow" + idf + "'><input type='text' class='haha{{ $errors->has('steps') ? ' is-invalid' : '' }}' name='steps[]' id='steps' /> <a href='#' style=\"color:#3399FD;\" onclick='hapusElemen(\"#srow" + idf + "\"); return false;'>Hapus</a></p>";
    $("#divHobi").append(stre);
    idf = (idf-1) + 2;
    document.getElementById("idf").value = idf;
}
function hapusElemen(idf) {
    $(idf).remove();
}

在使用dd()输入数据后,也会得到此结果

array:3 [0 => "banget" 
         1 => "asd"
         2 => "wwww"
]

在这种情况下,我试图将数组输入数据库并工作

这是代码

$hitung = $req->steps;
    $hitung2 = count($hitung);
    dd($hitung);

    for ($i=0; $i < $hitung2; $i++) { 
        $user = new TestCase;

        $user->id_test_case = $req->id_test_case;
        $user->id_document = $req->id_document;
        $user->test_scenario = $req->test_scenario;
        $user->post_condition = $req->post_condition;
        $user->pre_condition = $req->pre_condition;
        $user->expected_result = $req->expected_result;
        $user->steps = $req->steps[$i];
        $user->actual_result = $req->actual_result;
        $user->status = $req->status;
        $user->save();

    }

但是结果就像

This is result

然后我希望的预期结果是

Expected result

那有可能做到吗?没有循环?

1 个答案:

答案 0 :(得分:0)

您将在每个循环中创建一个新的TestCase;因此,您当然要在表中包含3行。摆脱循环,使用implode()steps设置为字符串:

$user = new TestCase;

$user->id_test_case = $req->id_test_case;
$user->id_document = $req->id_document;
$user->test_scenario = $req->test_scenario;
$user->post_condition = $req->post_condition;
$user->pre_condition = $req->pre_condition;
$user->expected_result = $req->expected_result;
$user->steps = implode(",", $req->steps);
$user->actual_result = $req->actual_result;
$user->status = $req->status;

$user->save();

现在将数组作为CSV值保存到数据库中不一定是最好的方法,因此请注意,根据该决定,您可能会遇到限制。考虑使用枢轴方法(usersstepsusers_steps)或类似方法。