嗯,我必须在数据库Bus and Station中的表中建立表,它们之间存在一对多关系,这是方案的问题-
这就是我所做的...
与车站的巴士关系
public function station()
{
return $this->belongsTo(Station::class);
}
与公交的状态关系
public function bus()
{
return $this->hasMany(Bus::class);
}
,这里是我在 Index Controller
中所做的事情// getting ther user id
$id= Sentinel::getUser()->id;
// fiding the statioin_id of that user_id and assigning it to variable
$user = User::find($id);
$s_id = $user->station_id;
// fiding the station which tht station_id belongs to and assign it to variable
$station = Station::find($s_id);
$stations_id = $station->id;
// getting buses of that specific station_id we just get and paginating it
$stationbus = Station::find($stations_id)->bus()->paginate();
return view('bus.index')->with('buses', $stationbus->bus);
,这是索引视图
当我执行上面的代码时,此错误将弹出
未定义的属性:Illuminate \ Pagination \ LengthAwarePaginator :: $ bus
再说一次,我的代码除了分页部分之外还可以正常工作。
答案 0 :(得分:0)
以下是我为改善您的代码而提出的一些建议:
在Station
模型中:
public function buses()
{
return $this->hasMany(Bus::class);
}
方法名称应为buses()
,因为它返回许多buses
,而不是单个bus
然后您的控制器代码可以如下重写:
$user= Sentinel::getUser();//So, you have the user
$station = Station::find($user->station_id);
//We don't need to query again, we already have the station. So...
$buses = $station->buses()->paginate();
return view('bus.index', compact('buses'));
因此,它更具可读性,紧凑性且执行的查询更少。