我是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
变量时出现问题。但我无法弄清楚,非常感谢帮助。
如果这个工程$ this-> cities() - > attach(2);那么你的问题可能在这里----> $ city = City :: where('name','=',$ waypoint) - > firstOrFail(); –
你可以尝试在哪里('名称','LIKE','%$ waypoint%“).....”=“通常不会与字符串发挥良好,除非它完全匹配 –
@HBensiali我尝试了你的想法并失败。但是当我在查询中使用了一个字符串时(例如'$ city = City :: where('name','LIKE',“cityname”) - > firstOrFail();')。查询得到执行。所以看起来变量不会在查询中分配值。 – anuh91