如何在 Laravel 5.2 中通过 ajax 请求将 Json 数组中的数据插入数据库


How to insert data in a Json array into a database via a ajax request in Laravel 5.2

我是Laravel的新手,使用的是5.2版。我有两个模型旅游和城市,两者之间有很多对多的关系。我已经通过数据库创建了 3 个表、旅游、城市和city_tour,并在模型中定义了关系。型号如下。

旅游模型

class Tour extends Model{
public function cities()
{
    return $this->belongsToMany('App'City');
}  }

城市模型

class City extends Model{
public function tours()
{
    return $this->belongsToMany('App'Tour');
}  }

我正在使用ajax post请求在我的TourController中传递数据存储方法。我的 ajax 请求如下。

$("#btnSave").click(function(){ 
    var path = JSON.stringify(route);
    var token = $('input[name="_token"]').val();
    $.post("/tour",
    {
        tourname: $("#name").val(),
        startpoint: $("#select_startpoint").val(),
        endpoint : $("#select_endpoint").val(),
        waypoints : path,
        '_token': token       
    },function(){
        alert("Path has been saved");
        window.location.href = "/tour";
    });
});

这里的变量路径是一个javascript数组,我已经将其转换为json字符串以传递给服务器。它包含城市名称作为字符串。

我的商店方法如下。

public function store(Request $request)
{   
    $tour = new Tour;
    $tour->tourname = $request->tourname;
    $tour->startpoint = $request->startpoint;
    $tour->endpoint = $request->endpoint;        
    $tour->save();
    $json = $request->waypoints;
    $waypoints= json_decode($json);
    foreach($waypoints as $point){
        $city = City::where('name', '=', $point->name)->firstOrFail();
        $cityid = $city->city_id;
        $tour->cities()->attach($cityid);  
    }  
    redirect()->action('TourController@index');
}

由于城市和旅游之间存在m:n关系,我想将我的城市添加到中间表中。在这里,由于我的城市在数组中,我检索了它们的city_id,并尝试使用 for each 循环将该 id 逐个附加到表中。我的代码如上。任何人都可以帮忙。

我相信您的代码需要更改如下:

从: $cityid = $city->city_id;

至: $cityid = $city->id;