gpt4 book ai didi

php - 在 Laravel 5.2 中将数据插入数据透视表

转载 作者:行者123 更新时间:2023-11-29 02:50:45 26 4
gpt4 key购买 nike

我是 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 在服务器中传递值。这里我使用RESTful资源 Controller 来处理请求,其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,因为我在数组中只有它的名称。当我执行代码时,游览表得到正确更新,但数据透视表 (city_tour) 没有。当我进一步调试时,我注意到自定义分配整数值时(例如:$tour->cities()->attach(2);)代码工作正常。将值分配给查询中的 $waypoint 变量似乎存在问题。但我无法弄清楚,非常感谢帮助。

最佳答案

您可以尝试 where('name', 'LIKE', "%$waypoint%")..... "="通常不能很好地处理字符串,除非它完全匹配。

SQL 中的 LIKE 获得最接近的匹配。将 % 与 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();

或者您不必使用 LIKE 但要确保 $city 在列中。

希望对你有帮助

关于php - 在 Laravel 5.2 中将数据插入数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com