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

标签 php mysql laravel laravel-4

我尝试将多个模型插入数据库,但没有成功...... 我有一个表格( 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/

相关文章:

mysql - 在 MySQL 中,为什么在使用未提交读时从 select 设置变量会获取锁?

mysql - 在连接中使用 where 子句时出现 Knex 错误

php - Laravel 5.2 用户表中的额外列

php - Laravel 验证 : Validating OR instead of AND

php - 使用 password_hash 时生成的哈希的最大长度?

javascript - 我们可以在组合图表中创建曲线吗?

php - 你能在 PHP 的类中使用静态常量吗?

mysql - 'tmp_run_date' 中的未知列 'field list'

Laravel 原始选择错误;在 mysql 中工作

php - 我应该如何在 phpmyadmin 中导入一个巨大的表