laravel mysql 数组,PHP如何使用laravel 5将数据从数组保存到mysql

Im getting an array within array of 'Cylinders' data from POST:

Array

(

[serie] => Array

(

[0] => 1234

[1] => 3545

)

[seriesap] => Array

(

[0] => 1234234

[1] => 345345

)

[type] => Array

(

[0] => 4546

[1] => csdfwe

)

[admission] => Array

(

[0] => 04-05-2015

[1] => 04-05-2015

)

[invoice] => Array

(

[0] => fei76867

[1] => feiasodjf

)

)

Now, the fields inside the keys: serie, type, admission, etc dont change, but the info inside those key do change, i mean there could be even 15 items in there.

At the end i need to save to the database:

$cylinder = new Cylinder();

$cylinder->serie = ??;

$cylinder->seriesap = ??;

$cylinder->type = ??;

$cylinder->admission = ??;

$cylinder->invoice = ??;

$cylinder->save

How can i accomplish this task and save all the cylinders?

I have tried all the foreach's that i could think of nothing seems to work.

/edit/

This is what Im doing so far:

$cyldata = $_POST['cylinder']; //this is the post from top.

$num_elements = 0;

while($num_elements < count($cyldata['serie'])){

$cylinder = new Cylinder();

$cylinder->serie = $cyldata['serie'][$num_elements];

$cylinder->type = $cyldata['type'][$num_elements];

$cylinder->admission = $cyldata['admission'][$num_elements];

$cylinder->seriesap = $cyldata['seriesap'][$num_elements];

$cylinder->save

$num_elements++;

}

But it feels ugly, all those saves doesnt feel right. Dirty solution if you ask me.

解决方案

First, you need to convert you input data to another format:

$cyldata = $_POST['cylinder']; //this is the post from top.

$num_elements = 0;

$sqlData = array();

while($num_elements < count($cyldata['serie'])){

$sqlData[] = array(

'serie' => $cyldata['serie'][$num_elements],

'type' => $cyldata['type'][$num_elements],

'admission' => $cyldata['admission'][$num_elements],

'seriesap' => $cyldata['seriesap'][$num_elements],

'invoice' => $cyldata['invoice'][$num_elements], // you miss this field, aren't you?

'created_at' => Carbon\Carbon::now(), // only if your table has this column

'updated_at' => Carbon\Carbon::now(), // only if your table has this column

);

$num_elements++;

}

Second, use the Fluent query builder to do a batch insert:

DB::table('table_name')->insert($sqlData);

Note: the created_at and updated_at appear here if your table has these field. When working with Eloquent model, these field is updated automatically. However, we do not use Eloquent, so that we have to assign the value to these field manually.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值