假设我有一个父系列的孩子,我想知道下一个兄弟是谁。我的父集合的排序与内部标识不同,因此我不能使用此处描述的方法:
Laravel previous and next records
哪个可行,除了我按名称和时间排序,而不是内部ID。我希望有一种方法可以获得父集合,找到这个孩子在其中的位置,然后在该集合中向前或向后看以获得下一个或上一个。
编辑:
所以,我做了这个,它起作用,但看起来很笨重。有没有更有效的方法来做到这一点?
public function next()
{
$previous = null;
foreach ($this->album->media as $media)
{
if(!empty($previous && $previous->id == $this->id))
{
// Yay! Our current record is the 'next' record.
return $media->id;
}
$previous = $media;
}
return null;
}
public function previous()
{
$previous = null;
foreach ($this->album->media as $media)
{
if(!empty($previous && $media->id == $this->id))
{
// Yay! Our previous record is the 'previous' record.
return $previous;
}
$previous = $media->id;
}
return null;
}
答案 0 :(得分:1)
你永远不应该加载整个表来遍历它以找到下一个/上一个项目,而是这样做:
$next = $this->album->media()->orderBy('id')->where('id', '>', $this->id)->first();
答案 1 :(得分:0)
这就是诀窍:
public function next()
{
$previous = null;
foreach ($this->album->media as $media)
{
if(!empty($previous && $previous->id == $this->id))
{
// Yay! Our current record is the 'next' record.
return $media->id;
}
$previous = $media;
}
return null;
}
public function previous()
{
$previous = null;
foreach ($this->album->media as $media)
{
if(!empty($previous && $media->id == $this->id))
{
// Yay! Our previous record is the 'previous' record.
return $previous;
}
$previous = $media->id;
}
return null;
}