嗯,我必须在我的数据库总线和车站中表,它们有一对多的关系,下面是场景的问题-
我就是这么做的..。
总线与站的关系
public function station()
{
return $this->belongsTo(Station::class);
}与总线的状态关系
public function bus()
{
return $this->hasMany(Bus::class);
}这是我在索引控制器中所做的
// 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
此外,除了分页部分之外,我的代码工作得很好。
发布于 2019-05-15 17:36:12
这里,是我的一些建议,使您的代码更好:
在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'));因此,它更具可读性、紧凑性和较少的可执行查询。
https://stackoverflow.com/questions/56154470
复制相似问题