在Eloquent中获取next / prev元素

时间:2015-05-27 13:36:14

标签: php laravel laravel-4 eloquent

我有产品和目录的模型。他们有很多关系,因此我使用名为' items'的数据透视表。我有一条路线:

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

我将产品模型和目录模型传递给视图,该视图输出产品信息和目录信息 - 非常简单。现在我需要2个按钮 - ' next'和之前的'浏览目录中的产品。

所以有一种方法可以做到这一点,我想我会在Catalog模型上创建两个方法来接受当前的产品模型,并根据ID返回next / prev模型:

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).

我不知何故需要从目录中获取next / prev项目,但无法弄清楚如何。任何建议都会非常感激。

3 个答案:

答案 0 :(得分:0)

您可以过滤收集,如下所示:

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

我使用添加到Collection类的全局方法:

/**
 * 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对象要求。

答案 1 :(得分:0)

您可以使用Pagination

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

答案 2 :(得分:0)

实际上,它要简单得多。这就是诀窍:

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

我必须在&#39; item&#39;之后添加()启用&#39; where&#39;条款并使其基本可搜索。

相关问题