我尝试将多个模型插入数据库,但没有成功...... 我有一个表格( Blade )如下所示:
@extends('layouts.properties')
@section('content')
{{ Form::open(['route' => 'properties.store', 'class' => 'uk-form', 'id' => 'properties-form']) }}
@for ($i = 0; $i < Auth::user()->properties_count; $i++)
<fieldset class="uk-margin-large-top property-field-{{ $i + 1 }}">
{{ Form::select('boro[]', ['Pick Borough', 'Manhattan', 'Bronx', 'Brooklyn', 'Queens', 'Staten Island']) }}
{{ Form::text('house_num[]', Input::old('house_num'), ['class' => 'uk-form-width-small', 'placeholder' => 'House Num']) }}
{{ Form::text('street[]', Input::old('street'), ['placeholder' => 'Street']) }}
</fieldset>
@endfor
{{ Form::submit('Save Properties', ['class' => 'uk-button uk-button-primary']) }}
{{ Form::close() }}
@stop
在 Controller 中,我有:(如果用户只填写了 2 个属性,则使用 array_filter 清除未设置的值)
$boro = array_filter(Input::get('boro'));
$house_num = array_filter(Input::get('house_num'));
$street = array_filter(Input::get('street'));
现在我陷入困境......无法弄清楚如何循环通过 3 个数组并将其保存到多个模型(行)。
注意:在我的用户模型中,我确实设置了 hasMany Properties 关系。
我的属性模型如下所示: ID 用户身份 博罗 豪斯努姆 街道
因此,如果在数组中我有 2 个地址,我需要行。
有什么想法吗?
最佳答案
// Get your input values
$boros = Input::get('boro');
$numbers = Input::get('house_num');
$streets = Input::get('street');
// Iterate through the arrays
$models = array();
$total = count($boros);
for( $c=0; $c < $total; $c++ ) {
$models[] = array('boro' => $boros[$c], 'numbers' => $numbers[$c], 'street' => $streets[$c]);
}
// Insert all the models
DB::table('whatever')->insert($models);
关于php - Laravel 4 - 如何插入多个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290401/