简体   繁体   English

如何在 Laravel 中不使用 foreach 存储请求数组?

[英]How can I store request array without using foreach in Laravel?

I have an array in the post request as an example below:我在 post 请求中有一个数组作为下面的例子:

$data = array(
    array('title'=>'1st title', 'desc'=>'desc'),
    array('title'=>'2nd title', 'desc'=>'desc'),
    array('title'=>'3rd title', 'desc'=>'desc'),
)

Is there a way in Laravel using Eloquent I can save above data without using foreach?有没有办法在 Laravel 中使用 Eloquent 我可以在不使用 foreach 的情况下保存上述数据? Note that the array keys which I am getting in the request is not same as column names of the table.请注意,我在请求中获得的数组键与表的列名不同。

I hope this would help you我希望这会帮助你

$data = [
    ['title' => '1st title', 'desc' => 'desc'],
    ['title' => '2nd title', 'desc' => 'desc']
    .....
];

DB::table('users')->insert($data);

Put all the values you want to insert in to an array and then pass it to the insert function.将所有要插入的值放入一个数组中,然后将其传递给 insert 函数。

Source: https://laravel.com/docs/5.1/queries#inserts来源: https : //laravel.com/docs/5.1/queries#inserts

尝试这个:

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

Using eloquent: just as mentioned by Sethu, but a few lines will be:使用 eloquent:正如 Sethu 所提到的,但有几行是:

Model::insert($data); // eg: Posts::insert($your_request_array);

Just pass in the array directly here: above will return true on success.只需直接在此处传入数组:上面将在成功时返回 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM