我有一个Laravel4.2项目,在这个项目中,我可以从SQL获得数据,并且可以在页面上显示。我可以选择单一的记录很好,但我也想显示周围的记录被选中。
例如,我想显示上面和下面所选的5条记录。我不知道如何在拉勒维尔做这件事。
$gradschoolrange = MOGRadschool::where('Title', '=', $gradschool)->get();在上面的例子中,$gradschool可能是"Test“,它将返回一个值,但我也想用这些值显示它周围的所有其他相关记录。结果应该是这样的:
发布于 2018-10-02 20:57:32
由于在初始查询中没有指定顺序,我假设您希望根据主键(id?-如果不是,显然需要更改表中的记录)来获得5个下一个/先前的记录?
考虑到ID可能不是数字顺序的,我们不能简单地假设前5行将是标题= $gradschool减去5的行的ID,因此想知道这是否可行:
$initial = MOGRadschool::where('Title', $gradschool)->first(); // get the initial row with the title of $gradschool
$result = MOGRadschool::where('id', '<', $initial->id)->take(5)->orderBy('id', 'DESC') // new query getting the previous 5 rows, by ID
->union(MOGRadschool::where('id', '>', $initial->id)->take(5)) // union a second query getting the next 5 rows by ID
->get() // get the result as a collection
->add($initial) // add the initial row to the collection
->sort(); // sort the collection (by id) so that the initial row is in the middle因此,输出是一个集合,包含中间的第一行,两边最多有5条记录。如果需要的话,您还可以使用初始行来突出显示输出。
发布于 2018-10-02 20:58:28
如果您想要基于I(这就是我从您的问题中了解到的),这样的方法应该可以:
$selectedGradSchool = MOGRadschool::where('Title', '=', $gradschool)->get()->first();
$aboveSelected = MOGRadschool::where('id', '<=', $selectedGradSchool->id)
->orderBy('id', 'desc')
->take('5')
->get();
$belowSelected = MOGRadschool::where('id', '>' $selectedgradSchool->id)
->take('5')
->get();
//Concatenate both results
$schoolRange = $aboveSelected->concat($belowSelected);现在,集合应该看起来类似于您想要的结果。
https://stackoverflow.com/questions/52615965
复制相似问题