Laravel Vue-存储阵列



我想将数组中的数据存储到数据库中。我的代码如下:

Vue.js

const self = this;
fetch('/api/store/devices',{
method: 'post',
body: JSON.stringify(self.devices),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
console.log(data);
// do something
})
.catch(err => console.log(err));
}

API路线

Route::post('store/devices',[AppHttpControllersStorageController::class, 'store']);

StorageController.php

public function store(Request $request)
{
//Go to array and save data
}

上面的数据看起来是这样的:

[
{device_id: "1245678", storage_id: 1},
{device_id: "8784889", storage_id: 1},
{device_id: "8457875", storage_id: 1}
]

如何存储这些数据?

首先,我建议将数组放入一个字段中,以便生成一个"开放扩展,封闭修改";api:

{
'devices': [
{device_id: "1245678", storage_id: 1},
{device_id: "8784889", storage_id: 1},
{device_id: "8457875", storage_id: 1}
]
}

其次,如果您试图保存设备和存储器之间的关系实例,则应该使用laravel关系方法。

如果这是一个单独的模型信息,请尝试下一个代码。

您必须迭代所有设备,并将其创建为您的laravel模型:

public function store(Request $request)
{
foreach ($request->devices as $device) {
YourModel::create($device); // if you had set $fillable attribute on your model
// or like this
$yourModel = new YourModel();
$yourModel->device_id = $device['device_id'];
$yourModel->storage_id = $device['storage_id'];
$yourModel->save(); // it saves yourModel into your db
}
}

YourModel可填充示例:

use IlluminateDatabaseEloquentModel;
<?php
class YourModel extends Model {
protected $fillable = [
'device_id',
'storage_id',
];
}

最新更新