我有一个采用以下结构的表单
<tr id='actionRow'>
<td>
<input type="text" name='actionInput[0][]' id="actionInput" placeholder='Action' class="form-control"/>
</td>
<td>
<select class="responsibility" name="actionInput[1][]" id="responsibilityInput">
<option value=""></option>
@foreach($users as $user)
<option value="{{ $user->userName }}">{{ $user->userName }}</option>
@endforeach
</select>
</td>
<td>
<input type="text" name='actionInput[2][]' id="dateInput" placeholder='Completion Date' class="form-control dateControl"/>
</td>
</tr>
我有一个选项供用户向这个表单添加行,它基本上克隆了表行。输出actionInput时,我在控制器中得到的最终结果如下所示
array:3 [▼
0 => array:3 [▼
0 => "Action Input 1"
1 => "Action Input 2"
2 => "Action Input 3"
]
1 => array:3 [▼
0 => "Responsibility Input 1"
1 => "Responsibility Input 2"
2 => "Responsibility Input 3"
]
2 => array:3 [▼
0 => "Date Input 1"
1 => "Date Input 2"
2 => "Date Input 3"
]
]
将此数据添加到我的数据库表时,表行应包含每个数组的一位数据。因此,如果我将上述数据插入数据库,我的表行应如下所示
Action | Responsibility | Date
-------------------------------------
Input 1 | Responsibility 1 | Date 1
-------------------------------------
Input 2 | Responsibility 2 | Date 2
-------------------------------------
Input 3 | Responsibility 3 | Date 3
-------------------------------------
在我的控制器中,我目前正在这样做
$actions = Input::get('actionInput');
foreach($actions as $action => $category) {
$contactReportActions = new ContactReportActionsDoc();
$contactReportActions->contactReportId = $contactReport->id;
foreach($category as $key => $value){
$contactReportActions->action = $value;
$contactReportActions->responsibility = $value;
$contactReportActions->deliveryDate = $value;
}
$contactReportActions->save();
}
问题是,产生类似下面的内容
Action | Responsibility | Date
----------------------------------------------------------
Input 1 | Input 2 | Input 3
----------------------------------------------------------
Responsibility 1 | Responsibility 2 | Responsibility 3
----------------------------------------------------------
Date 1 | Date 2 | Date 3
----------------------------------------------------------
那么我怎样才能在我的控制器中纠正这个问题,以便正确地将数据输入我的数据库?
由于
答案 0 :(得分:1)
我会做这样的事情:
<tr id='actionRow'>
<td>
<input type="text" name="actionInput[{{$key}}]['action']" id="actionInput" placeholder='Action' class="form-control"/>
</td>
<td>
<select class="responsibility" name="actionInput[{{$key}}]['responsibility']" id="responsibilityInput">
<option value=""></option>
@foreach($users as $user)
<option value="{{ $user->userName }}">{{ $user->userName }}</option>
@endforeach
</select>
</td>
<td>
<input type="text" name="actionInput[{{$key}}]['date_input']" id="dateInput" placeholder='Completion Date' class="form-control dateControl"/>
</td>
</tr>
在视图中,您应该为数组生成随机或顺序键,并使用其名称存储表的列。对于稍后克隆的每一行,您将生成另一个密钥。
如果需要,此布局还允许更轻松的实体编辑。
然后,在Controller中,您可以像这样分隔每个实体属性:
foreach (\Input::get('actionInput', array()) as $entityData)
{
$entity = ContactReportAction::find($entityData["id"]) ?: new ContactReportAction;
$entity->fill($entityData);
$entity->save();
}
检查这是否对您有帮助......