我有一个商店,您可以通过单击按钮导航到下一个/上一个产品。
我使用了本教程:http://laravel-tricks.com/tricks/get-previousnext-record-ids
我的问题是,有4个I的某些产品,我想跳过。我根本不想展示这些。
我该怎么做?
以下是我的尝试:
@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的产品,只是没有下一个/前一个按钮。
我的路线:
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]+');发布于 2015-03-03 07:31:52
有几个建议:
你想把复杂的逻辑排除在你的视野之外。确定前一个/下一个ids不是您的视图的责任。这些值应该传入。
另外,您可能需要考虑将路由中的逻辑移动到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));
}https://stackoverflow.com/questions/28819831
复制相似问题