duanjiuhong5843 2014-06-18 16:12
浏览 122

Laravel 4 - 如何插入多个模型?

Im trying to insert multiple models into the database but with no luck... I have a form (blade) looks like this:

@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

In the controller, I have: (used array_filter to clear the unset values if the user only filled in 2 properties)

$boro = array_filter(Input::get('boro'));
$house_num = array_filter(Input::get('house_num'));
$street = array_filter(Input::get('street'));

Now I'm stuck... can't figure it out how to loop thru 3 arrays and save it to multiple models (rows).

Note: In my User model I did set hasMany Properties relationship.

My Property model looks like: id user_id boro housenum street

So if in the arrays i have 2 addresses, I need to rows.

Any ideas?

  • 写回答

2条回答 默认 最新

  • doucheng2210 2014-06-18 18:09
    关注
    // 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);
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度