【问题标题】:Laravel: how to paginate a ' One to Many ' Relationship?Laravel:如何对“一对多”关系进行分页?
【发布时间】:2019-10-02 21:36:45
【问题描述】:

嗯,我必须在我的数据库 Bus 和 Station 中使用表,它们有一对多的关系,这是场景的问题-

  1. 一个车站可以有多辆公交车。
  2. 5 到 10 辆公交车不需要分页,但如果 Station 有 100 或 1000 辆公交车怎么办。这种方法太可怕了。

这就是我所做的......

与车站的巴士关系

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

再一次,我的代码除了分页部分之外工作正常。

【问题讨论】:

  • 在您的->with() 方法中,$stationbus->bus 不应该只是$stationbus吗?
  • @TimLewis 我怎么错过了!谢谢,伙计,你拯救了我的一天。
  • 不用担心。它发生了 :) 如果您不知道 LengthAwarePaginator is 是什么,则该错误有点模糊,但通常当您看到“未定义的属性 X”时,查找 $something->X,您应该会找到罪魁祸首。干杯!

标签: laravel laravel-5 pagination relationship


【解决方案1】:

这里是我的一些建议,以使您的代码更好:

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'));

因此,它更易读、更紧凑并且执行的查询更少。

【讨论】:

  • 我不认为这会变魔术。我们上面的朋友@Tim 帮了我一个忙,这是我犯的一个简单错误,但无论如何,谢谢,兄弟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2015-04-23
  • 2020-06-28
相关资源
最近更新 更多