2015-03-02 27 views
0

我有一個商店,您可以通過單擊按鈕導航到下一個/上一個產品。瀏覽頁面標識除了某些標識 - laravel

我用這個教程:http://laravel-tricks.com/tricks/get-previousnext-record-ids

我的問題是有我想跳過某些產品的4個IDS。我不想顯示這些。

我該怎麼做?

這裏是我的嘗試:

@unless($product->id == 17 || $product->id == 18 || $product->id == 20 || $product->id == 22 ) 

    <?php 
     $previous = Product::where('id', '<', $product->id)->max('id'); 

     $next = Product::where('id', '>', $product->id)->min('id'); 
    ?> 

    <a href="{{URL::to('products/'.$previous)}}" id="prevProd"><i class="fa fa-angle-left"></i></a> 
    <a href="{{URL::to('products/'.$next)}}" id="nextProd"><i class="fa fa-angle-right"></i></a> 
@endunless 

如果我在路線做這個呢?這不起作用。它仍然顯示帶有這些ID的產品,它只是沒有下一個/上一個按鈕。

我的路線:

Route::get('products/{id}', function($id) 
{ 
    $oProduct = Product::find($id); 

    return View::make('singleproduct')->with('product', $oProduct)->with("cart",Session::get("cart")); 

})->where('id', '[0-9]+'); 

回答

1

一對夫婦建議:

你想嘗試和保持複雜的邏輯出你的看法。確定上一個/下一個ID不是您的觀點責任。這些值應通過。

另外,您可能需要考慮將路由中的邏輯移動到Controller中。所有的路線應該是指向應該運行的控制器/方法。實際處理任何邏輯(在發送應用程序的地方之外)並不是路線的工作。最後,就您的功能而言,您可能需要考慮將邏輯提取到產品模型上的某個方法。雖然,我不會讓它成爲模型範圍方法,因爲您返回的是值而不是查詢對象。沿着線的東西:

public function getNextId(array $except = null) { 
    $query = $this->where('id', '>', $this->id); 
    if (!empty($except)) { 
     $query->whereNotIn('id', $except); 
    } 
    return $query->min('id'); 
} 

public function getPreviousId(array $except = null) { 
    $query = $this->where('id', '<', $this->id); 
    if (!empty($except)) { 
     $query->whereNotIn('id', $except); 
    } 
    return $query->max('id'); 
} 

現在,在你的路線(或者,如果你移動到控制器),你可以這樣做:

function($id) { 
    $excludeIds = array(17, 18, 20, 22); 
    // you may want some logic to handle when $id is one of the excluded 
    // ids, since a user can easily change the id in the url 
    $oProduct = Product::find($id); 
    return View::make('singleproduct') 
     ->with('product', $oProduct) 
     ->with('cart', Session::get('cart')) 
     ->with('previous', $oProduct->getPreviousId($excludeIds)) 
     ->with('next', $oProduct->getNextId($excludeIds)); 
} 
+0

傳奇!謝謝你。並提供建議。我是新的,並沒有在我的模型中放置太多的邏輯。很高興看到它是如何完成的。這很好用!以防其他人想要使用它,模型函數中有一個錯字。哪裏不在哪裏沒有。再次感謝! – 2015-03-03 21:08:41

+0

@thomasjaunism對不起。修復了代碼錯字。感謝您指出了這一點。很高興我能幫上忙。 – patricus 2015-03-03 21:37:01