在Eloquent中获取下一个/上一个元素


Get next / prev element in Eloquent

我有一个产品和目录的模型。它们之间存在多对多的关系,因此我使用了一个名为"items"的数据透视表。我有一条路由:

/something/something/{catalogue}/{product}

我将产品模型和目录模型传递给视图,视图输出产品信息和目录信息——非常直接。现在我需要有2个按钮-"下一个"answers"上一个"通过目录中的产品导航。

因此,要做到这一点,我认为我将在catalog模型上创建2个方法,它们将接受当前产品模型并根据ID返回下一个/上一个模型:

public function prevProduct($product){              
    $prevProdId = Product::where('id', '<', $product->id)->max('id');
    return Product::find($prevProdId);
}
public function nextProduct($product){        
    $nextProdId = Product::where('id', '>', $product->id)->min('id');
    return Product::find($nextProdId);
}

现在可以正常工作了,但是您可以看到,它从数据库中的product表中检索下一个产品和上一个产品,而不是从目录中检索。

要获取目录中的所有产品,可以这样做:$this->items (on Catalogue model) or $catalogue->items (from view).

我需要从目录中找到下一个/上一个项目,但不知道怎么做。如有任何建议,不胜感激。

您可以对Collection进行筛选,如下所示:

$next = $item->id + 1;
$catalogue->filter(function($item) use ($next ) {
                return $item->id == $next;
            })->first(); 

我使用全局方法添加到集合类:

/**
 * Returns first object from collection which meets attribute criteria
 * 
 * @param string $attributeName   name of attribute we are looking for
 * @param string $attributeValue  value of attribute that have to be met
 * @return 'Illuminate'Database'Eloquent'Collection
 */
public function findByAttribute($attributeName, $attributeValue)
{
    return $this->filter(function($item) use ($attributeName, $attributeValue) {
        return $item->{$attributeName} == $attributeValue;
    })->first();        
}

在本例中,我将这样使用这个方法:

$catalogue->items->findByAttribute('id', $next);

在这两个例子中,我假设您有$item对象来引用

可以使用分页

Catalogue::first()->items()->paginate(1);

其实要简单得多。

$nextProdId = $this->items()->where('product_id', '>', $product->id)->min('product_id');        
return Product::find($nextProdId);

我必须在"items"之后添加()来启用"where"子句,并使其基本可搜索。