我在处理json多个数据时遇到问题。我没有得到多个数据,如果我使用“数组”,它还会在数据库中创建具有空值的单个记录。
用于保存数据的后端代码
`![caption](imagepath)`
我需要类似的响应,并且应该将其保存到数据库中
{
$pickup = new PickupData();
$pickup->pickup_person = $request->pickup_person;
$pickup->office_city = $request->office_city;
$pickup->office_state = $request->office_state;
$pickup->office_pincode = $request->office_pincode;
$pickup->pickup_email = $request->pickup_email;
$pickup->preferred_start_time = $request->preferred_start_time;
$pickup->preferred_end_time = $request->preferred_end_time;
$pickup->mobile = $request->mobile;
$pickup_date = Carbon::parse($request->pickup_date)->format('d-m-Y');
$pickup->pickup_date = $pickup_date;
$saved = $pickup->save();
}
答案 0 :(得分:1)
php artisan make:resource PickupResourceCollection
php artisan make:resource PickupResource
use use App\Http\Resources\PickupResourceCollection;
...
public function index()
{
$pickups = Pickup::all();
return response()->json(new PickupResourceCollection($pickups),200);
}
...
....
public function toArray($request)
{
return [
'data' => $this->collection->transform(function ($pickups) {
return new PickupResource($pickups);
})
];
}
....
....
public function toArray($request)
{
return [
"pickup_person" =>$this->pickup_person,
"city" =>$this->city,
"office_address" =>$this->office_address,
"office_city" =>$this->office_city,
"office_state" =>$this->office_state,
"office_pincode" =>$this->office_pincode,
"pickup_email" =>$this->pickup_email,
"preferred_start_time"=>$this->preferred_start_time,
"preferred_end_time" =>$this->preferred_end_time,
"mobile" =>$this->mobile,
"pickup_date" =>"$this->pickup_date
];
}
....
就这样:)
答案 1 :(得分:0)
是的,您可以将其另存为数组。
$pickup = PickupData::create($request->all()) // to save all request data
$pickup = PickupData::create($request->except(['var1', 'var2'])) // to save all request data except var1 & var2
$pickup
将仅返回新插入的行。
答案 2 :(得分:0)
$pickupDetails = [
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office@gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
},
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office@gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
}
];
$pickupDetails = $request->all();
foreach($pickupDetails as $pickup){
Pickup::create($pickup);
}
return response()->json("success",200);
如果它可以帮助您支持我:)