如何在同一列数据库中保存多行输入?

时间:2015-04-22 13:58:51

标签: php mysql laravel laravel-4 eloquent

数据库表

id  | title | reading | writing | speaking

form.blade.php

<table><tr>
    <th>Language</th>
    <th>Reading</th>
    <th>Writing</th>
    <th>Speaking</th>
</tr>
<tr>
    <td>
        <input name="TitleText_1" id="TitleText_1"/></td>
    <td>
        <select name="ReadingText_1" id="ReadingText_1">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
        </select>
    </td>
    <td>
        <select name="langWrittingText_1" id="WrittingText_1">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
        </select>
    </td>
    <td>
        <select name="SpeakingText_1" id="SpeakingText_1">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
        </select>
    </td>
</tr>
<tr>
    <td>
       <input name="TitleText_2" id="TitleText_2" /></td>
    <td>
        <select name="ReadingText_2" id="ReadingText_2">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
        </select>
    </td>
    <td>
        <select name="WrittingText_2" id="WrittingText_2">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
    </select>
    </td>
    <td>
        <select name="SpeakingText_2" id="SpeakingText_2">
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
        </select>
    </td>

LanguageController.php

   $languages = Language::create(array

   (

   'title' => $input['TitleText_1'],

   'reading' => $input['ReadingText_1'],

   'writting' => $input['WrittingText_1'],

   'speaking' => $input['SpeakingText_1'],
$languages->save();

  ));

我想要将控制器代码保存到数据库中。因为有多个相同标签的输入。

如何获取控制器中的所有输入?如何将多个输入保存到同一列的数据库中?我是Laravel 4.2的新手。

1 个答案:

答案 0 :(得分:2)

使用具有相同名称的多个输入,例如

<input name="TitleText[]" />
<select name="ReadingText[]" >
...
<select name="langWrittingText[]">
...
<select name="SpeakingText[]">
...

这样,数据将以数组的形式发布。 假设所有输入/选择都需要由用户填写

在你的控制器中你可以做这样的事情

$count = count($input['TitleText']); // here we will know how many entries have been posted
$languages = array();
for($i=0; $i<$count; $i++){
   if(!empty($input['TitleText'][$i])){
     array_push($languages, array( // iterate through each entry and create an array of inputs
      'title' => $input['TitleText'][$i], 
      'reading' => $input['ReadingText'][$i], 
      'writting' => $input['WrittingText'][$i],
      'speaking' => $input['SpeakingText'][$i]
     ));
   }
}
Languages::insert($languages); // save the array of models at once

希望这有帮助。