所以根据您的问题。
以下 JSON 将起作用。
JSON 中会有一个订单数组,其中有多个订单,如下所示:
{
"user_id": 1
"orders": [
{"product_name": "Whatever1 is selected", "quantity": 1},
{"product_name": "Whatever2 is selected", "quantity": 2},
{"product_name": "Whatever3 is selected", "quantity": 3},
],
}
然后在服务器端:
public function store(Request $request)
{
// after validating this you can use foreach to parse the the json
foreach($request->orders as $order)
{
//suposse you have orders table which has user id
Order::create([
"product_name" => $order['product_name'],
"quantity" => $order['quantity'],
"user_id" => $request->user_id // since this is just json object not an jsonarray
]);
}
}
如果你使用 Laravel Passport,那么你不需要在 JSON 中指定 user_id。在这种情况下,您的 JSON 将如下所示:
{
"orders": [
{"product_name": "Whatever1 is selected", "quantity": 1},
{"product_name": "Whatever2 is selected", "quantity": 2},
{"product_name": "Whatever3 is selected", "quantity": 3},
],
}
然后在你的控制器中的服务器端:
public function store(Request $request)
{
// after validating this you can use foreach to parse the the json
foreach($request->orders as $order)
{
//suposse you have orders table which has user id
Order::create([
"product_name" => $order['product_name'],
"quantity" => $order['quantity'],
"user_id" => Auth::id() // since you are using passport
]);
}
}
api.php 文件中的路由:
Route::post('user/order','OrderController@store');
// if using Laravel Passport
Route::post('user/order','OrderController@store')->middleware('auth:api');
这就是您可以使用护照而不使用护照包将同一用户的多个订单存储在 JSON 中的方法。
注意:您可以根据自己的设计更改 json 键名。
这只是一个示例,让您了解如何使用它。