【问题标题】:How to save array of objects to mysql database in laravel?如何在laravel中将对象数组保存到mysql数据库?
【发布时间】:2018-02-25 07:15:22
【问题描述】:

我在 laravel 中使用 vue。我正在尝试保存对象数组,但无法保存,尽管我能够保存单个对象。这是我的代码 应用程序.vue

// Not working
saveData(){
  this.axios.post('/addperson', **this.rows**).then((response) => {
    console.log("WOW");
  })
}

//working
    saveData(){
      this.axios.post('/addperson', **this.rows[0]**).then((response) => {
        console.log("WOW");
      })
    }

这是控制器代码,当我传递数组时出现错误。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\OrderPerson;

class PersonController extends Controller
{
  public function create(Request $request){

      $person = new Person([
        'name' => $request->get('name'),
        'age' => $request->get('age'),
        'user_id' =>$request->get('user_id')''
      ]);

      $person->save();
    return response()->json('Successfully added');
  }
}

谁能帮我保存数组?

【问题讨论】:

标签: php laravel vue.js


【解决方案1】:

首先将所有 this.rows 分配给一个数据集,然后将其推送到 axios 调用,如下所示:

saveData(){
    const postData = {
            data: this.rows
        }
  this.axios.post('/addperson', postData).then((response) => {
    console.log("WOW");
  })
}

现在在laravel 控制器中,您可以使用foreach 来使用这个数据集。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\OrderPerson;

class PersonController extends Controller
{
  public function create(Request $request){

    foreach($request->data as $data)
    {
        $container = new Person([
            'name' => $data['name'],
            'age' => $data['age'],
            'user_id' => $data['user_id']
          ]);

        $container->save();
    }

    return response()->json('Successfully added');
  }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2017-06-22
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 2011-02-06
    • 2021-08-23
    相关资源
    最近更新 更多