我有多个Chapter
属于 a 的 s Module
。
在章节页面上,我想检查我是否在模块中的最后一个,但我有点卡住了。
// inside Chapter model.
// The $module var is a made by something like Module::with('chapters')->find(1);
public function getNext($module){
// Convert to array so we can call some of
// the array functions to navigate the array
$chapters = $module->chapters->keyBy('id')->toArray();
// get the last element in the array
end($chapters);
// If the last element's key is the same as this one,
// there is no "next" link
if(key($chapters) == $this->id){
return false;
}
// So there must be a next link. First, reset internal array pointer
reset($chapters);
// Advance it to the current item
while (key($chapters) !== $this->id) next($chapters);
// Go one further, returning the next item in the array
next($chapters);
// current() is now the next chapter
return current($chapters);
}
凉爽的!所以这让我知道是否有下一章,甚至将它作为包含所有数据的数组返回。但是我遇到了很多问题。上面还有Chapter
一些其他方法,我不能将“下一个”元素作为数组调用,而不是对象。
// Chapter.php
public function url(){
return url('chapter/' . $this->id);
}
$module = Module::with('chapters')->find(1);
$chapter = Chapter::find(1);
$next = $chapter->getNext($module);
if( $next )
echo $next->url();
这给了我(显然)
调用数组上的成员函数 url()
所以我需要重写这个函数,但我不知道如何获取 Laravel 集合中的下一个对象。
public function getNext($module){
$last = $module->chapters->last();
// If the last element's key is the same as this one,
// there is no "next" link
if($last->id == $this->id){
return false;
}
....
如何遍历集合以获取下一章作为对象?