使用" slugs"通过另一个表ID获取项目

时间:2015-01-24 20:17:30

标签: laravel eloquent slug

我有一个非常简单的数据库模型,包含两个表项和类别。

项目表

ID I Title I Category_id

类别表

ID I Name I Slug

此时我可以使用类似www.myapp.com/tags/1的特定类别过滤项目。

Route::get('tags/{category?}', array('as'=>'itemstag', 'uses'=>'ItemsController@show_items'));

这就是控制器的样子。

   public function show_items($category = NULL)
{

    if($category == NULL)
        return View::make('items/index', ['items' => Item::where('publishtime', '<', date('Y-m-d H:i:s'))->orderBy('created_at','Desc')->paginate(24),'categories' => Category::all()]);
    else
        return View::make('items/index', ['items' => Item::where('publishtime', '<', date('Y-m-d H:i:s'))->orderBy('created_at','Desc')->where('category_id','=',$category)->paginate(24),'categories' => Category::all()]);

}

问题是我想让我的网址更“漂亮”但是如果我将slu pass传递给控制器​​那么我就无法评估条件,因为我的项目模型上没有$ slug。我应该在这里加入吗?在这种情况下实施slug的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

    $items = Item::where('publishtime', '<', date('Y-m-d H:i:s'))
         ->orderBy('created_at','Desc')
         ->whereHas('category', function ($q) use ($category){
             $q->where('slug','=',$category);
         })
         ->paginate(24);