复杂查询并通过 slug 而不是 laravel 中的 ID 获取结果

Complex query and getting results by slug instead of ID in laravel

我有复杂的查询和关系,但我并不完全理解。我是 Laravel 的新人。无论如何,我正在寻找一种方法来使用 slugs 而不是 ID 来加载它。

这是控制器中的函数

public function index( $category_id)
{
    $Category = new Category;
    $allCategories = $Category->getCategories();
    $category = Category::find($category_id);

    if($category->parent_id == 0) {

         $ids = Category::select('id')->where('parent_id', $category_id)->where('parent_id','!=',0)->get();
         $array = array();

         foreach ($ids as $id) {
            $array[] = (int) $id->id;
         }
         $items = Item::whereIn('category_id',$array)->where('published', 1)->paginate(5);

    } else {
        $items =  Item::where('category_id' ,$category_id)->where('published', 1)->paginate(5);
    }

    return view('list', compact('allCategories','items'));
}

这些是模型中的关系

public function item()
{
    return $this->hasMany('App\Item','category_id');
}

public function children()
{
    return $this->hasMany('App\Category', 'parent_id');
}


public function getCategories()
{
    $categoires = Category::where('parent_id',0)->get();
    $categoires = $this->addRelation($categoires);
    return $categoires;
}
public function selectChild( $id )
{
    $categoires = Category::where('parent_id',$id)->where('published', 1)->paginate(40);
    $categoires = $this->addRelation($categoires);
    return $categoires;
}

public function addRelation( $categoires )
{

  $categoires->map(function( $item, $key)
  {             
        $sub = $this->selectChild($item->id);
        $item->itemCount = $this->getItemCount($item->id , $item->parent_id );
        return $item = array_add($item, 'subCategory', $sub);
    });
    return $categoires;
}
public function getItemCount( $category_id )
{
    return Item::where('category_id', $category_id)->count();
} 

这是我的路线

Route::get('list/{category}', 'ListController@index')->name('list');

目前正在加载类似 http://example.com/list/1 where 1 is the ID. I'm wonder if with current setup is possible to make it like, http://example.com/slug

的网址

我知道鼻涕虫是如何工作的。我只是不明白如何在查询中使用它们而不是 ID

尝试将索引函数参数从 $category_id 更改为 $category_slug

删除这一行$Category = new Category;

并更改此 $category = Category::find($category_id);

为此:$category = Category::where('slug', $category_slug)->first();

*假设您在类别 table

中有唯一 slug

您可以在处理之前使用 explicit Route Model Binding 通过 slug 抓取您的类别。

在您的RouteServiceProvider中您需要绑定模型:

Route::bind('category', function ($value) {
   //Change slug to your column name
   return App\Category::where('slug', $value)->firstOrFail();  
});

然后,您可以输入类别提示。

例如在你的索引方法中:

public function index(Category $category)
{
    $Category = new Category;
    $allCategories = $Category->getCategories();
    //This line is obsolete now:
    //$category = Category::find($category_id);

    //...
}