首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >浏览页面ids,但某些ids除外- laravel

浏览页面ids,但某些ids除外- laravel
EN

Stack Overflow用户
提问于 2015-03-02 21:33:45
回答 1查看 85关注 0票数 0

我有一个商店,您可以通过单击按钮导航到下一个/上一个产品。

我使用了本教程:http://laravel-tricks.com/tricks/get-previousnext-record-ids

我的问题是,有4个I的某些产品,我想跳过。我根本不想展示这些。

我该怎么做?

以下是我的尝试:

代码语言:javascript
复制
@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 

我应该在我的路线上做这个吗?这不管用。它仍然显示带有这些It的产品,只是没有下一个/前一个按钮。

我的路线:

代码语言:javascript
复制
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]+');
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-03 07:31:52

有几个建议:

你想把复杂的逻辑排除在你的视野之外。确定前一个/下一个ids不是您的视图的责任。这些值应该传入。

另外,您可能需要考虑将路由中的逻辑移动到Controller中。所有的路由都应该指向应该运行的控制器/方法。实际处理任何逻辑(在发送应用程序的地方之外)并不是路由的工作。

最后,就功能而言,您可能需要考虑将逻辑提取到产品模型上的方法中。不过,我不会让它成为一个模型范围方法,因为您返回的是一个值,而不是一个查询对象。与…有关的东西:

代码语言:javascript
复制
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');
}

现在,在您的路由(或控制器,如果您移动到它),您可以做:

代码语言:javascript
复制
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));
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28819831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档