首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拉勒维尔:如何分页‘一对多’的关系?

拉勒维尔:如何分页‘一对多’的关系?
EN

Stack Overflow用户
提问于 2019-05-15 17:10:41
回答 1查看 1K关注 0票数 0

嗯,我必须在我的数据库总线和车站中表,它们有一对多的关系,下面是场景的问题-

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

我就是这么做的..。

总线与站的关系

代码语言:javascript
复制
public function station()
{
    return $this->belongsTo(Station::class);
}

与总线的状态关系

代码语言:javascript
复制
public function bus()
{
    return $this->hasMany(Bus::class);
}

这是我在索引控制器中所做的

代码语言:javascript
复制
//  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

此外,除了分页部分之外,我的代码工作得很好。

EN

回答 1

Stack Overflow用户

发布于 2019-05-15 17:36:12

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

Station模型中:

代码语言:javascript
复制
public function buses()
{
    return $this->hasMany(Bus::class);
}

方法名应该是buses(),因为它正在返回许多buses,而不是单个bus

然后您的控制器代码可以重写如下:

代码语言:javascript
复制
$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'));

因此,它更具可读性、紧凑性和较少的可执行查询。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56154470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档