【问题标题】:Laravel 4 - How to insert multiple models?Laravel 4 - 如何插入多个模型?
【发布时间】:2014-08-09 00:50:53
【问题描述】:

我正在尝试将多个模型插入数据库但没有运气... 我有一个表格(刀片)看起来像这样:

@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

在控制器中,我有:(如果用户只填写了 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 属性关系。

我的属性模型如下所示: ID 用户身份 波罗 房子 街道

所以如果在数组中我有 2 个地址,我需要行。

有什么想法吗?

【问题讨论】:

  • 我不太明白你的问题。你能指定你的模型是什么样的以及你想插入哪些数据吗?
  • 我已经编辑了原帖,希望现在很清楚......
  • 请更具体地了解您的模型,保存的值是某种关系?真的没有冒犯,但代码有点不可读。那么究竟是什么问题呢?
  • 我不知道我能有多清楚...

标签: php mysql laravel laravel-4


【解决方案1】:
// 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);

【讨论】:

    【解决方案2】:
    $boros = Input::get('boro');
    $streets = Input::get('street');
    $numbers = Input::get('house_num');
    
    $properties = [];
    
    foreach ($boros as $key => $boro)
    {
       $properties[] = [
         'boro' => $boro, 
         'street' => $streets[$key], 
         'housenum' => $numbers[$key],
         'user_id' => $userId   // probably needed too
       ]
    }
    
    // cleaning (and validation maybe?)
    $properties = array_map(function ($property) {
        return array_filter($property);
    }, $properties);
    
    
    DB::table('properties')->insert($properties);
    

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2014-07-17
      • 2015-12-21
      • 2013-07-20
      • 2013-01-30
      • 1970-01-01
      相关资源
      最近更新 更多