简体   繁体   English

我如何遍历这个关联数组并将其保存到数据库中?

[英]how do i loop through this associative array and save it to the database?

I have this request coming into server in this format, how do I save it into the database, I am new to Laravel and also I have three models, Trip(where the first 4 key value pairs are stored), Location(where the source and destination array are stored ) and then the categories are stored in a Category model我有这个请求以这种格式进入服务器,我如何将它保存到数据库中,我是 Laravel 的新手,而且我有三个模型,Trip(存储前 4 个键值对的位置),位置(源的位置和目标数组存储),然后类别存储在类别 model

{
    "name": "glass cup",
    "weight" : "12kg",
    "quantity": 400,
    "source": {
         "longitude":122324,
         "latitude":231242,
         "address": "this is just a new address",
         "place_id":23234
    },
    "destinations": [
        {
             "longitude":122324,
             "latitude":231242,
             "address": "this is just a new address",
             "place_id":23234
        },
        {
            "longitude":122324,
            "latitude":231242,
            "address": "this is just a new address",
            "place_id":23234
        },
        {
            "longitude":122324,
            "latitude":231242,
            "address": "this is just a new address",
            "place_id":23234
        }
    ],
    "categories": ["food", "clothes", "utensils"]

}

Either you save it as JSON or you create the proper fileds to insert in database.要么将其保存为 JSON,要么创建适当的文件以插入数据库。 Plus, dunno if you have any relationship between the tables, but to insert data you do something like:另外,不知道表之间是否有任何关系,但是要插入数据,您可以执行以下操作:

$trip = new \App\Models\Trip;
$trip->name = $request->name;
$trip->weight = $request->weight;
$trip->quantity = $request->quantity;
$trip->save();

For destinations you just loop the items:对于目的地,您只需循环项目:

foreach ($request->destinations as $dest)
{
    $location = new \App\Models\Location;
    $location->longitude = $dest->longitude;
    $location->latitude = $dest->latitude;
    $location->address = $dest->address;
    $location->place_id = $dest->place_id;
    $location->save();
}

If you'd like to save the trip id in the location table, just use $location->trip_id = $trip->id;如果您想将trip id保存在location表中,只需使用$location->trip_id = $trip->id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM