2015-05-27 34 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); 

我不得不添加()後「項目」,使「其中」條款,並使其基本搜索。