doujiu6976
doujiu6976
2019-04-11 10:58
浏览 89
已采纳

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

I have an array in the post request as an example below:

$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? Note that the array keys which I am getting in the request is not same as column names of the table.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doushi9729
    doushi9729 2019-04-11 11:02
    已采纳

    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.

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

    点赞 评论
  • duanqiang5722
    duanqiang5722 2019-04-11 11:12

    try this:

    DB::table('table_name')->insert($data);
    
    点赞 评论
  • douzi2333
    douzi2333 2019-04-11 11:12

    Using eloquent: just as mentioned by Sethu, but a few lines will be:

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

    Just pass in the array directly here: above will return true on success.

    点赞 评论

相关推荐