【发布时间】:2016-03-28 08:59:56
【问题描述】:
我是 Laravel 的新手。我正在使用 Laravel 5.2,并且在将数据插入数据透视表时遇到了问题,我曾经用它来处理多对多关系。为了将数据传递到服务器,我使用了 jquery ajax post 请求。代码如下。
$("#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 在 server.xml 中传递值。这里我使用了一个 RESTful 资源控制器来处理请求,它的 store 方法如下。
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,因为数组中只有它的名称。
当我执行代码时,游览表会正确更新,但数据透视表 (@987654324@) 不会。当我进一步调试时,我注意到自定义分配整数值时(例如:$tour->cities()->attach(2);)代码工作正常。将值分配给查询中的$waypoint 变量似乎存在问题。但我无法弄清楚,非常感谢帮助。
【问题讨论】:
-
如果可行 $this->cities()->attach(2);那么你的问题可能就在这里----> $city = City::where('name', '=', $waypoint)->firstOrFail();
-
你可以试试 where('name', 'LIKE', "%$waypoint%" )..... "=" 通常不能很好地使用字符串,除非它完全匹配
-
@HBensiali 我尝试了你的想法但失败了。但是当我在查询中只使用一个字符串时(例如
$city = City::where('name', 'LIKE', "cityname" )->firstOrFail();)。查询被执行。所以看起来变量没有在查询中赋值。 -
嘿,您必须在两侧添加 % 符号。 $city = City::where('name', 'LIKE', "%$cityname%" )->firstOrFail();无论如何.... LIKE 是必须的字符串。 '=' 用于处理整数或布尔值等绝对值
标签: php mysql pivot-table laravel-5.2