2016-03-28 150 views
2

我是Laravel的新手。我正在使用Laravel 5.2,并且在将数据插入到用于处理多对多关系的数据透视表中时遇到了问题。为了将数据传递给服务器,我使用了jquery ajax post请求。它的代码如下。在Laravel 5.2中插入数据到数据透视表中

$("#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传递服务器中的值。在这里,我使用RESTful资源控制器来处理请求,其存储方法如下。

public function store(Request $request){ 
    $user = Auth::user(); 

    $tour = new Tour; 
    $tour->name = $request->tourname; 
    $tour->user_id = $user->id; 
    $tour->startpoint = $request->startpoint; 
    $tour->endpoint = $request->endpoint; 
    $tour->save(); 

    $json = $request->waypoints; 
    $waypoints = json_decode($json); 

    foreach($waypoints as $waypoint){   
     $city = City::where('name', '=', $waypoint)->firstOrFail();  
      $tour->cities()->attach($city->id);     
    } } 

在这里,在插入数据透视表我想从数据库中获取特定城市的city_id第一,因为我只有它在数组中的名字。 当我执行代码旅游表得到正确更新,但数据透视表(city_tour)does'nt。当我进一步调试时,我发现当一个整数值被自定义分配时(例如:$tour->cities()->attach(2);)代码工作正常。看起来在将值分配给查询中的$waypoint变量时出现问题。但我无法弄清楚,非常感谢帮助。

+0

如果这个工程$ this-> cities() - > attach(2);那么你的问题可能在这里----> $ city = City :: where('name','=',$ waypoint) - > firstOrFail(); –

+1

你可以尝试在哪里('名称','LIKE','%$ waypoint%“).....”=“通常不会与字符串发挥良好,除非它完全匹配 –

+0

@HBensiali我尝试了你的想法并失败。但是当我在查询中使用了一个字符串时(例如'$ city = City :: where('name','LIKE',“cityname”) - > firstOrFail();')。查询得到执行。所以看起来变量不会在查询中分配值。 – anuh91

回答

1

你可以尝试在哪里('name','LIKE',“%$ waypoint%”).....“=”通常不能很好地与字符串搭配,除非它完全匹配。

LIKE in SQL获得最接近的匹配。 使用%和LIKE:

寻找城市'阿尔及尔'。 这将找到城市

$city = 'Algiers'; 
City::where('name', 'LIKE', "$city")->firstOrFail(); 

,如果你有一个白色的空间,然后如果你使用%,那么空间或字符被忽略你可能会得到什么

$city = ' Algiers'; 
City::where('name', 'LIKE', "$city")->firstOrFail(); 

$city = ' Algiers'; //extra space on the end 
City::where('name', 'LIKE', "%$city")->firstOrFail(); 

,或者如果你想从单词的末尾忽略任何不同之处:

$city = 'Algier'; //with 's' missing 
City::where('name', 'LIKE', "$city%")->firstOrFail(); 

或者你没有使用像,但你确保$城市在列。

希望可以帮到

相关问题