我需要将数组添加到数据库表中。在HTML中,我使用具有多个选择值的select。
我的代码: HTML如:
<select name="sel_val[]" multiple>
<optgroup label="select_values">
@foreach($val as $v)
<option value="{{$v->id}}">{{$v->text}}</option>
@endforeach
</optgroup>
</select>
模型关系如:
public function relationtest(){
return $this->hasMany('App\test',"testid","id");
}
和控制器:
protected function create(Request $request){
$last = Home::create([
'somename'=>$request['somename'],
'text'=>$request['text']
]);
$last->relationtest()->createMany([
'selectvalue'=>$request->sel_val
]);
return Redirect::to('admin/products');
}
我的数组(print_r($ request)):
[sel_val] => Array ( [0] => 1 [1] => 3 )
和DB
HOME::
|id|sometext|text
|1 |asdgasdg|gsdg
|2 |asdgdsdg|gsg
TEST::
|id|selectvalue|testid
//testid == HOME::id
简而言之,我需要将$ request-&gt; sel_val(数组)添加到数据库中。我想我应该使用&#34; createMany&#34;但我不知道怎么做。
答案 0 :(得分:1)
简化使用这样的事情:
$values = $request->get('sel_val');
foreach ($values as $value)
{
$last->relationtest()->create(['selectvalue' => $value]);
}
如果要将其优化为一个查询,请务必使用createMany:
$values = $request->get('sel_val');
$toCreate = [];
foreach ($values as $value)
{
$toCreate[] = ['selectvalue' => $value];
}
$last->relationtest()->createMany($toCreate);