【发布时间】:2016-06-05 04:45:42
【问题描述】:
我是 Laravel 的新手,使用的是 5.2 版。我有两个模型 Tour 和 City,它们之间有多对多的关系。我已经在数据库中创建了 3 个表、旅游、城市和 city_tour,并在模型中定义了关系。 型号如下。
旅游模型
class Tour extends Model{
public function cities()
{
return $this->belongsToMany('App\City');
} }
城市模型
class City extends Model{
public function tours()
{
return $this->belongsToMany('App\Tour');
} }
我正在使用 ajax 发布请求在我的 TourController 中传递数据存储方法。我的 ajax 请求如下。
$("#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";
});
});
这里的变量 path 是一个 javascript 数组,我已将其转换为 json 字符串以便传递给服务器。它包含城市名称作为字符串。
我的Store方法如下。
public function store(Request $request)
{
$tour = new Tour;
$tour->tourname = $request->tourname;
$tour->startpoint = $request->startpoint;
$tour->endpoint = $request->endpoint;
$tour->save();
$json = $request->waypoints;
$waypoints= json_decode($json);
foreach($waypoints as $point){
$city = City::where('name', '=', $point->name)->firstOrFail();
$cityid = $city->city_id;
$tour->cities()->attach($cityid);
}
redirect()->action('TourController@index');
}
由于 City 和 Tour 之间存在 m:n 关系,我想将我的城市添加到中间表中。在这里,由于我的城市位于数组中,因此我检索了他们的 city_id 并尝试使用 for each 循环将该 id 逐个附加到表中。我的代码如上。谁能帮忙。
【问题讨论】:
-
向我们展示
path变量的结构。 -
@ZakariaAcharki 结构是这样的
["City1","City2","City3","City3","City4"] -
:( 那么为什么你在
$point->name中获得name属性,而它不存在? -
@ZakariaAcharki 我的错。然后我将代码更改为
$city = City::where('name', '=', $point)->firstOrFail();但是数据只保存到tours表中,它不会将数据保存到city_tour表中。 -
好的尝试添加模型代码然后我们可以检查关系是否正确。
标签: php ajax pivot-table laravel-5.2