[英]How to Populate MySQL Database with JSON array of objects in Laravel?
[英]How to save array of objects to mysql database in laravel?
我正在與laravel一起使用vue。 我正在嘗試保存對象數組,但是盡管我能夠保存單個對象,卻無法做到。 這是我的代碼App.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');
}
}
任何人都可以幫助我保存陣列嗎?
首先,將所有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');
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.