【问题标题】:Inserting data in to a pivot table in Laravel 5.2在 Laravel 5.2 中将数据插入数据透视表
【发布时间】: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


【解决方案1】:

你可以试试 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 在列中。

希望有帮助

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2020-09-19
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多