[英]How to split array and only save specific value into database? Laravel with Ajax
我有个问题。 我需要将数组保存到数据库中,但我需要先对其进行划分,并且只保存特定的值。 我正在使用 Ajax 并将数据传递给控制器。
ps:数组集合可以超过1个,所以每个集合都需要根据数据库中的列进行拆分和存储。
我的包含 Ajax 的 javascript:
Hotspot.prototype.saveData = function (data) { if (!data.length) { return; } // Get previous data var raw_data = localStorage.getItem(this.config.LS_Variable); var hotspots = []; if (raw_data) { hotspots = JSON.parse(raw_data); } // Append to previous data $.each(data, function (index, node) { hotspots.push(node); }); console.log(hotspots); // var field=JSON.stringify(hotspots).split(','); this.data=data; $.ajax({ type:"POST", url:"/store", dataType:'json', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data:{ Title: JSON.stringify(hotspots), Message: JSON.stringify(hotspots), x: JSON.stringify(hotspots), y: JSON.stringify(hotspots), }, success: function(data){ console.log(data,d); }, error: function(data) { console.log(data); }, }); localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots)); this.element.trigger('afterSave.hotspot', [null, hotspots]); };
控制器:
public function storePin(Request $request)
{
request()->validate([
'Title' => 'required',
'Message' => 'required',
'x'=> 'required',
'y'=>'required',
]);
dd($request);
if ($request->all())
{
$pin = new Pin();
$pin->Title=json_encode($request->input('Title'));
$pin->Message= json_encode($request->input('Message'));
$pin->x = json_encode($request->input('x'));
$pin->y =json_encode($request->input('y'));
$pin->save();
// return response()->json_encode($request);
}
}
示例输出:
Title: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
Message: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
x: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
y: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
基于此,我只希望它只存储:
Title:only save title
Message:save message
x:save x
y save y
只需传入整个热点数组,例如:
data: hotspots,
然后在您的模型中进行任何格式化并插入许多:
// some formatting to create data array
$data = [];
foreach($hotspots as $hotspot){
$data[] = [
'Title' => $hotspot['Title'],
'Message' => $hotspot['Message'],
'x' => $hotspot['x'],
'y' => $hotspot['y'],
];
}
Pin::insert($data);
问题似乎是将data
解析为hotspots
。 此方法迭代每个data
条目,然后分配完整节点。
$.each(data, function(index, node) {
hotspots.push(node);
});
每个属性定义都使用完整的hotspots
对象,而不是一个属性。
data: {
Title: JSON.stringify(hotspots),
Message: JSON.stringify(hotspots),
x: JSON.stringify(hotspots),
y: JSON.stringify(hotspots),
},
你可能需要做这样的事情:
{
Title: hotspots[0].Title,
Message: hotspots[0].Message,
x: hotspots[0].x,
y: hotspots[0].y,
}
即便如此,该解决方案仍然缺少一些重要信息。 例如, hotspots
应该是一组hotspot
对象……你怎么知道你要为单个请求发送哪个?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.