2015-05-27 38 views
1

我有一个产品和目录的模型。他们有很多关系,因此我使用了一个名为'items'的数据透视表。我有一个路线:在Eloquent中获取下一个/上一个元素

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

我传递的产品型号和目录模型视图,它输出的产品信息和目录信息 - 非常直截了当。现在我需要有2个按钮 - “下一个”和“上一个”来浏览目录中的产品。

所以一个办法做到这一点,我想我会根据ID创建2种方法对目录模式,将接受目前的产品型号,并返回一个/上一个模型:

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

不知何故,我需要从目录下一个/上一个项目,但无法弄清楚如何。任何建议将不胜感激。

回答

0

您可以过滤收集,就像这样:

$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对象来反驳。

0

您可以使用Pagination

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

其实,这是简单得多。这奏效了:

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

我不得不添加()后“项目”,使“其中”条款,并使其基本搜索。